﻿var HDDGallery = new Class({
    Implements: Options,
    options: {
        slideInterval: 5000
    },
    
    initialize: function(options) {
        this.setOptions(options);
        this.container = $('gallery_container');
        this.tagtitle = $('tagtitle');
        this.deckoptions = $('deck_options');
        this.deckinfo = $('deckinfo');
        this.galleryscroller = $('gallery_scroller');
        this.index = 0;
        this.pagesize = 16;
        
        this.setupEvents();
    },
    
    setupEvents: function() {
        var el = $('photosearch');
        if (el) el.addEvent('keydown', function(event) { if (event.key == 'enter') { event.stop(); this.search(); }}.bind(this));
        el = $('photosubmit');
        if (el) el.addEvent('click', function() { this.search(); }.bind(this));
    },
    
    search: function() {
        var el = $('photosearch');
        if (el) {
            if (el.value.length == 0)
                alert('Please enter your search criteria');
            else
                window.location.href = '/decks/search.aspx?q=' + escape(el.value);
        }
    },
    
    show: function(category, tag, deck) {
        this.category = category;
        this.tag = tag;
        this.clear();
        
        this.tagtitle.set('text', tag.Name);
        this.index = 0;
        if (this.category.ID == 0) {
            this.decks = this.getFavorites();
            this.decks.length == 0 ? new Element('div', { 'styles': { 'margin-top': '10px' }}).set('text', 'You have not added any decks to your favourites list.').inject(this.container) : this.showThumbnails();
        }
        else {
            new Element('img', { 'class': 'loading', 'src': '/images/gallery/loading.gif' }).inject(this.container);
            new Element('span').set('text', ' Loading...').inject(this.container);
            var url = '/data/decks.aspx?category=' + this.category.ID + '&tag=' + this.tag.ID;
            new Request.JSON({ 'url': url, 'method': 'get', 'onSuccess': function(result) {
                    this.decks = result;
                    this.index = 0;
                    
                    var deck_index = -1;
                    if (deck) {
                        for (var i=0; i<this.decks.length; i++) {
                            if (this.decks[i].ID == deck) {
                                deck_index = i;
                                break;
                            }
                        }
                    }
                    deck_index == -1 ? this.showThumbnails() : this.showDeck(deck_index);
                }.bind(this)}).get();
        }
    },

    changePageSize: function() {
        this.pagesize = parseInt(this.pageSizeSelect.value);
        this.moveTo(0);
    },
    
    showPageSizeOptions: function() {
        this.pageSizeSelect = new Element('select', { 'styles': { 'float': 'right' }, 'events': { 'change': function() {
                this.changePageSize();
            }.bind(this)}}).inject(this.container);
        new Element('option', { 'value': '8' }).set('text', '8').inject(this.pageSizeSelect);
        new Element('option', { 'value': '16' }).set('text', '16').inject(this.pageSizeSelect);
        new Element('option', { 'value': '24' }).set('text', '24').inject(this.pageSizeSelect);
        new Element('option', { 'value': '32' }).set('text', '32').inject(this.pageSizeSelect);
        new Element('option', { 'value': '5000' }).set('text', 'all').inject(this.pageSizeSelect);
        this.pageSizeSelect.value = this.pagesize;
        
        new Element('span', { 'styles': { 'float': 'right', 'margin-right': '4px' }}).set('text', 'Pictures Per Page:').inject(this.container);
    },
    
    showThumbnails: function() {
        this.clear();
        this.showPageSizeOptions();
        var container = new Element('div', { 'id': 'thumbnails' }).inject(this.container);
        this.tagtitle.set('text', this.tag.Name);

        if (this.index < 0 || this.index > this.decks.length) this.index = 0;
        var last_index = this.index + this.pagesize;
        if (last_index > this.decks.length) last_index = this.decks.length;
        
        new Element('div', { 'styles': { 'font-style': 'italic', 'margin-bottom': '8px' }}).set('text', 'Please click on an image to view larger').inject(container);

        for (var i=this.index; i<last_index; i++) {
            var deck = this.decks[i];
            new Element('img', { 'src': '/picture.aspx?s=s&id=' + deck.PictureID, 'styles': { 'float': 'left', 'border': 'none', 'height': '67px', 'width': '102px', 'margin': '1px', 'cursor': 'pointer' }, 'events': { 'click': 
                (function(index) { 
                    return function() { this.showDeck(index); this.buildThumbnailScroller(index); }; }
                )(i).bind(this)}}).inject(container);
        };
        new Element('div', { 'class': 'clear' }).inject(container);
        
        var bottom = new Element('div', { 'styles': { 'float': 'left', 'height': '18px', 'width': '100px' }}).inject(container);
        if (this.index > 0)
            new Element('a', { 'class': 'whitebold', 'styles': { 'float': 'left', 'padding': '2px' }, 'events': { 'click': function() {
                    this.moveTo(this.index - this.pagesize);
                }.bind(this)}}).set('text', '◄ PREVIOUS').inject(bottom);

        bottom = new Element('div', { 'styles': { 'padding-top': '2px', 'text-align': 'center', 'float': 'left', 'height': '16px', 'width': '214px' }}).inject(container);
        
        bottom = new Element('div', { 'styles': { 'float': 'left', 'height': '18px', 'width': '100px' }}).inject(container);
        if (this.index + this.pagesize < this.decks.length)
            new Element('a', { 'class': 'whitebold', 'styles': { 'float': 'right', 'padding': '2px' }, 'events': { 'click': function() {
                    this.moveTo(this.index + this.pagesize);
                }.bind(this)}}).set('text', 'NEXT ►').inject(bottom);
                
        new Element('div', { 'id': 'video', 'styles': { 'float': 'left', 'text-align': 'left', 'margin': '0 0 0 10px' }}).inject(this.deckoptions);
        new VideoPlayer('HDD9.mp4', 'video_brad3.jpg');
    },
    
    moveTo: function(index) {
        if (index < 0 || index > this.decks.length) index = 0;
        this.index = index;
        this.showThumbnails();
    },
    
    showDeck: function(index) {
        var deck = this.decks[index];
        this.deckIndex = index;
        this.clear(['galleryscroller','slider']);
        
        // title
        this.tagtitle.set('text', (this.category.ID == 0 ? 'My Favourites' : this.tag.Name) + ' - Deck ID H' + deck.ID);
        
        // image
        new Element('img', { 'id': 'deckimage', 'src': '/picture.aspx?s=m&id=' + deck.PictureID, 
            'events': { 'click': function() { this.showLargeImage(deck); }.bind(this)}}).inject(this.container);
        
        // utilities
        new Element('img', { 'src': '/images/gallery/gallerysub_back.jpg', 'class': 'rollover', 'events': {
            'click': function() { this.showThumbnails(); }.bind(this) }}).inject(this.deckoptions);
        new Element('img', { 'src': '/images/gallery/gallerysub_view.jpg', 'class': 'rollover', 'events': {
            'click': function() { this.showLargeImage(deck); }.bind(this) }}).inject(this.deckoptions);
        new Element('img', { 'src': '/images/gallery/gallerysub_inquire.jpg', 'class': 'rollover', 'events': {
            'click': function() {
                this.modalize();
                var top = (window.getHeight()-400)/2;
                var left = (window.getWidth()-400)/2;
                this.dialogcontainer = new Element('div', { 'styles': { 'position': 'absolute', 'cursor': 'pointer', 'top': top, 'left': left, 'height': '400px', 'width': '400px', 'z-index': 60, 'background-color': '#fff', 'padding': '0px', 'border': 'solid 4px #0e8545' }}).inject(document.body);
                new Element('div', { 'styles': { 'background-color': '#0e8545', 'padding': '2px', 'color': '#fff', 'font-weight': 'bold' }}).set('text', 'INQUIRE ABOUT THIS DECK').inject(this.dialogcontainer);
                new Element('iframe', { 'frameborder': 'no', 'styles': { 'width': '400px', 'height': '380px', 'border': 'none' }, 'src': 'inquire.aspx?deck=' + deck.ID }).inject(this.dialogcontainer);
            }.bind(this) }}).inject(this.deckoptions);
        new Element('img', { 'src': '/images/gallery/gallerysub_email.jpg', 'class': 'rollover', 'events': {
            'click': function() {
                this.modalize();
                var top = (window.getHeight()-300)/2;
                var left = (window.getWidth()-400)/2;
                this.dialogcontainer = new Element('div', { 'styles': { 'position': 'absolute', 'cursor': 'pointer', 'top': top, 'left': left, 'height': '300px', 'width': '400px', 'z-index': 60, 'background-color': '#fff', 'padding': '0px', 'border': 'solid 4px #0e8545' }}).inject(document.body);
                new Element('div', { 'styles': { 'background-color': '#0e8545', 'padding': '2px', 'color': '#fff', 'font-weight': 'bold' }}).set('text', 'EMAIL TO FRIEND').inject(this.dialogcontainer);
                new Element('iframe', { 'frameborder': 'no', 'styles': { 'width': '400px', 'height': '280px', 'border': 'none' }, 'src': 'sendtofriend.aspx?deck=' + deck.ID }).inject(this.dialogcontainer);
            }.bind(this) }}).inject(this.deckoptions);
        if (this.category.ID == 0) {
            new Element('img', { 'src': '/images/gallery/gallerysub_remove.jpg', 'class': 'rollover', 'events': {
                'click': function() {
                    this.removeFavorite(deck);
                    this.showThumbnails();
                }.bind(this) }}).inject(this.deckoptions);
        }
        else {
            new Element('img', { 'src': '/images/gallery/gallerysub_add.jpg', 'class': 'rollover', 'events': {
                'click': function() {
                    this.addFavorite(deck);
                    alert('The deck has been added to your favourites list');
                }.bind(this) }}).inject(this.deckoptions);
        }
        new Element('img', { 'src': '/images/gallery/gallerysub_bookmark.jpg', 'class': 'rollover', 'events': {
            'click': function() {
                title = 'HICKORY DICKORY DECKS - DECK H' + deck.ID;
                url = 'http://www.hickorydickorydecks.com/decks/?tag=' + this.tag.ID + '&deck=' + deck.ID;
                if (window.sidebar) // Mozilla
                    window.sidebar.addPanel(title, url, "");
                else if( window.external ) // IE
                   window.external.AddFavorite( url, title);
            }.bind(this) }}).inject(this.deckoptions);
        if (deck.DeckPlan) {
            new Element('img', { 'src': '/images/gallery/gallerysub_deck.jpg', 'class': 'rollover', 'events': {
                'click': function() {
                    this.modalize();
                    var top = (window.getHeight()-400)/2;
                    var left = (window.getWidth()-480)/2;
                    this.dialogcontainer = new Element('div', { 'styles': { 'position': 'absolute', 'cursor': 'pointer', 'top': top, 'left': left, 'height': '400px', 'width': '480px', 'z-index': 60, 'background-color': '#fff', 'padding': '0px', 'border': 'solid 4px #0e8545' }}).inject(document.body);
                    new Element('div', { 'styles': { 'background-color': '#0e8545', 'padding': '2px', 'color': '#fff', 'font-weight': 'bold' }}).set('text', 'PURCHASE DECK PLANS').inject(this.dialogcontainer);
                    new Element('iframe', { 'frameborder': 'no', 'styles': { 'width': '480px', 'height': '380px', 'border': 'none' }, 'src': 'deckplan.aspx?tag=' + this.tag.ID + '&deck=' + deck.ID }).inject(this.dialogcontainer);
                }.bind(this) }}).inject(this.deckoptions);
        }
        if (rollovers) rollovers.update();

        // deck information
        this.deckinfo.setStyle('display', 'block');
        
        // additional photos
        this.showAdditionalPhotos(deck);

        // description
        new Element('div', { 'class': 'description' }).set('text', deck.Description).inject(this.deckinfo);
        
        // pre-load next photo
        var ondeck = this.deckIndex+1;
        if (ondeck == this.decks.length) ondeck = 0;
        new Asset.images('/picture.aspx?s=m&id=' + this.decks[ondeck].PictureID);
        
        // move to thumbnail
        if (this.thumbScroller) this.thumbScroller.scrollToElement('thumb' + deck.PictureID);
    },
    
    buildThumbnailScroller: function(startIndex) {
        var scroller = new Element('div', { 'class': 'scroller' }).inject(this.galleryscroller);
        new Element('div', { 'class': 'previous' }).inject(scroller);
        var images = new Element('div', { 'class': 'images' }).inject(scroller);

        for (var i=0; i<this.decks.length; i++) {
            var deck = this.decks[i];
            new Element('img', { 'id': 'thumb' + this.decks[i].PictureID, 'rel': '/picture.aspx?s=s&id=' + this.decks[i].PictureID, 'events': { 'click': 
                (function(index) { 
                    return function() { this.showDeck(index); }; }
                )(i).bind(this)}}).inject(images);
        }
        new Element('div', { 'class': 'next' }).inject(scroller);
        this.playButton = new Element('div', { 'class': 'play', 'title': 'Play', 'events': { 'click': function() { this.toggleSlideshow(); }.bind(this)}}).inject(scroller);
        
        this.thumbScroller = new Scroller(scroller, { 'startIndex': startIndex });
        this.thumbScroller.addEvent('jump', function(direction) {
            switch (direction) {
                case 'previous':
                    if (this.deckIndex > 0)
                        this.showDeck(this.deckIndex - 1);
                    break;
                case 'next':
                    if (this.deckIndex < (this.decks.length - 1))
                        this.showDeck(this.deckIndex + 1);
                    break;
            }
        }.bind(this));
    },
    
    showAdditionalPhotos: function(deck) {
        if (deck.HasAdditionalPhotos) {
            // check if additional photos have been loaded yet
            if (!deck.AdditionalPhotos) {
                // send ajax request for photos
                var url = '/data/additionalphotos.aspx?deck=' + deck.ID;
                new Request({ 'url': url, 'method': 'get', 'onSuccess': function(result) {
                        if (result == "none" || result.length == 0)
                            deck.HasAdditionalPhotos = false;
                        else {
                            deck.AdditionalPhotos = [];
                            deck.AdditionalPhotos[0] = deck.PictureID;
                            var parts = result.split(',');
                            parts.each(function(p) {
                                deck.AdditionalPhotos[deck.AdditionalPhotos.length] = parseInt(p);
                            });
                            this.showAdditionalPhotos(deck);
                        }
                    }.bind(this)}).get();
            }
            else {
                // display photos
                var scroller = new Element('div', { 'class': 'scroller' }).inject(this.deckinfo);
                new Element('div', { 'class': 'previous' }).inject(scroller);
                var images = new Element('div', { 'class': 'images' }).inject(scroller);

                deck.AdditionalPhotos.each(function(p) {
                    new Element('img', { 'id': 'thumb' + p, 'src': '/picture.aspx?s=s&id=' + p, 'events': { 'click': function() { this.swapImage(p); }.bind(this) }}).inject(images);
                }.bind(this));

                new Element('div', { 'class': 'next' }).inject(scroller);
                new Element('div', { 'class': 'play', 'events': { 'click': function() { this.toggleSlideshow(); }.bind(this)}}).inject(scroller);
             
                new Scroller(scroller, { 'visibleItems': 5, 'scrollAction': 'scroll' });
            }
        }
    },
    
    swapImage: function(id) {
        var el = $('deckimage');
        if (el) el.src = '/picture.aspx?s=m&id=' + id;
    },

    showLargeImage: function(deck) {
        $clear(this.slider);
        this.slider = null;
        if (this.playButton) {
            this.playButton.set('title', 'Play');
            this.playButton.removeClass('pause');
        }

        this.modalize();

        var img_width = 960; var img_height = 643;
        var top = Math.max(window.getScroll().y, ((window.getHeight() - img_height - 40) / 2) + window.getScroll().y);
        var left = (window.getWidth() - img_width - 4) / 2;
        this.largecontainer = new Element('div', { 'styles': { 'position': 'absolute', 'cursor': 'pointer', 'top': top, 'left': left, 'height': 'auto', 'width': '960px', 'z-index': 60, 'background-color': '#fff', 'padding': '0px', 'border': 'solid 4px #0e8545' }}).inject(document.body);
        new Drag.Move(this.largecontainer);
        var largetitle = new Element('div', { 'styles': { 'height': '20px', 'width': 'auto', 'background-color': '#0e8545', 'padding': '0 0 2px 6px', 'color': '#fff', 'font-weight': 'bold', 'font-size': '12pt' }}).inject(this.largecontainer);
        new Element('div', { 'styles': { 'float': 'left' }}).set('text', '# H' + deck.ID).inject(largetitle);
        
        new Element('a', { 'styles': { 'float': 'right', 'margin': '2px 6px 0 0', 'color': '#fff', 'cursor': '#fff' }, 'events': { 'click': function() {
                this.unmodalize();
                this.largecontainer.destroy();
            }.bind(this)}}).set('text', 'Click here to return to the Hickory Dickory Decks photo gallery').inject(largetitle);
        new Element('img', { 'src': $('deckimage').src.replace('s=m', 's=l'), 'styles': { 'border': 'none' }}).inject(this.largecontainer);
    },
        
    startSlideshow: function(index) {
        if (index >= this.decks.length) index = 0;
        this.showDeck(index, true);
    },
    
    closeDialog: function() {
        if (this.backing) this.backing.destroy();
        if (this.dialogcontainer) this.dialogcontainer.destroy();
    },
    
    scrollAdditionalPhotos: function(container, index) {
        container.empty();
        
        var deck = this.decks[this.deckIndex];
        var end = Math.min(index + 4, deck.AdditionalPhotos.length);

        // add left scroller
        var scroll_left = new Element('img', { 'src': '/images/decks/left.png', 'styles': { 'border': 'none', 'cursor': 'pointer' }}).inject(container);
        if (index > 0) scroll_left.addEvents({
            'mouseover': function() { this.src = '/images/decks/left_ov.png'; },
            'mouseout': function() { this.src = '/images/decks/left.png'; },
            'click': function() { this.scrollAdditionalPhotos(container, index-1);}.bind(this)
        });
        
        // add images        
        for (var i=index; i<end; i++) {
            new Element('img', { 'src': '/picture.aspx?id=' + deck.AdditionalPhotos[i], 'styles': { 'margin': '0 1px 0 1px', 'border': 'none', 'cursor': 'pointer', 'width': '110px', 'height': '74px' }, 'events': {
                    'click': (function(index) { return function() {
                        var el = $('deckimage');
                        if (el) el.src = '/picture.aspx?s=m&id=' + deck.AdditionalPhotos[index];
                    }; })(i)
                }}).inject(container);
        }
        
        // add right scroller
        var scroll_right = new Element('img', { 'src': '/images/decks/right.png', 'styles': { 'border': 'none', 'cursor': 'pointer' }}).inject(container);
        if (index < deck.AdditionalPhotos.length-4) scroll_right.addEvents({
            'mouseover': function() { this.src = '/images/decks/right_ov.png'; },
            'mouseout': function() { this.src = '/images/decks/right.png'; },
            'click': function() { this.scrollAdditionalPhotos(container, index+1);}.bind(this)
        });
    },
    
    modalize: function() {
        var size = window.getScrollSize();
        this.backing = new Element('div', { 'styles': { 'position': 'absolute', 'top': 0, 'left': 0, 'height': size.y, 'width': size.x, 'background-color': '#ccc', 'opacity': '0.7', 'z-index': 50 }}).inject(document.body);
    },
    
    unmodalize: function() {
        if (this.backing) {
            this.backing.destroy();
            this.backing = null;
        }
    },
    
    toggleSlideshow: function() {
        if (this.slider) {
            $clear(this.slider);
            this.slider = null;
            if (this.playButton) {
                this.playButton.set('title', 'Play');
                this.playButton.removeClass('pause');
            }
        }
        else {
            this.slideNext();
            this.slider = this.slideNext.periodical(this.options.slideInterval, this);
            if (this.playButton) {
                this.playButton.set('title', 'Pause');
                this.playButton.addClass('pause');
            }
        }
    },
    
    slideNext: function() {
        var next = this.deckIndex + 1;
        if (next >= this.decks.length) next = 0;
        this.showDeck(next);
    },

    clear: function(exceptions) {
        // clears out all timers and erases all added content
        // except that specified in the exceptions array
        if (!exceptions) exceptions = [];
        
        if (!exceptions.contains('slider')) {
            $clear(this.slider);
            this.slider = null;
            if (this.playButton) {
                this.playButton.set('title', 'Play');
                this.playButton.removeClass('pause');
            }
        }
        if (!exceptions.contains('container')) this.container.empty();
        if (!exceptions.contains('title')) this.tagtitle.set('text', '');
        if (!exceptions.contains('deckoptions')) this.deckoptions.empty();
        if (!exceptions.contains('deckinfo')) {
            this.deckinfo.empty();
            this.deckinfo.setStyle('display', 'none');
        }
        if (!exceptions.contains('galleryscroller')) this.galleryscroller.empty();
    },
    
    getFavorites: function() {
        if (!this.FavoriteDecks) {
            // format: ID||PictureID|Name|HasAdditionalPhotos|DeckPlan~ID||PictureID|Name|HasAdditionalPhotos|DeckPlan
            this.FavoriteDecks = [];
            
            // read from cookie
            var value = '';
	        var ca = document.cookie.split(';');
	        for(var i=0; i<ca.length; i++) {
		        var c = ca[i];
		        while (c.charAt(0)==' ') c = c.substring(1,c.length);
		        if (c.indexOf('favdecks=') == 0) {
		            value = c.substring(5,c.length);
		            break;
		        }
	        }
    	    
	        // add to collection
            value.split('~').each(function(item) {
                var parts = item.split('|');
                if (parts.length == 5) {
                    var o = {};
                    o.ID = parseInt(parts[0]);
                    o.PictureID = parseInt(parts[1]);
                    o.Description = parts[2];
                    o.HasAdditionalPhotos = parts[3];
                    o.DeckPlan = false;
                    this.FavoriteDecks[this.FavoriteDecks.length] = o;
                }
            }.bind(this));
        }
        return this.FavoriteDecks;
    },


    
    addFavorite: function(deck) {
        // check if the deck is already in the collection
        var found = false;
        if (this.FavoriteDecks) {
            this.FavoriteDecks.each(function(fav) {
                if (fav.ID == deck.ID)
                    found = true;
            });
            if (found) return;
        }
        else {
            this.FavoriteDecks = [];
        }
        
        // add to collection
        var o = {};
        o.ID = deck.ID;
        o.PictureID = deck.PictureID;
        o.Description = deck.Description;
        o.HasAdditionalPhotos = deck.HasAdditionalPhotos;
        o.DeckPlan = false;
        this.FavoriteDecks[this.FavoriteDecks.length] = o;
        
        this.cookieFavorites();
    },
    
    removeFavorite: function(deck) {
        for (var i=0; i<this.FavoriteDecks.length; i++) {
            if (this.FavoriteDecks[i].ID == deck.ID) {
                this.FavoriteDecks.splice(i,1);
                break;
            }
        }
        this.cookieFavorites();
    },
    
    cookieFavorites: function() {
        var value = '';
        for (var i=0; i<this.FavoriteDecks.length; i++) {
            if (i>0) value += '~';
            value += this.FavoriteDecks[i].ID + '|' + this.FavoriteDecks[i].PictureID + '|' + this.FavoriteDecks[i].Description + '|' + this.FavoriteDecks[i].HasAdditionalPhotos + '|' + this.FavoriteDecks[i].DeckPlan;
        }
    	    var date = new Date();
	    date.setTime(date.getTime()+(365*24*60*60*1000));
	    var expires = "; expires="+date.toGMTString();
	    document.cookie = 'favdecks='+value+expires+'; path=/';
    }
});

function closeDialog() {
    gallery.closeDialog();
}

