// Utility
var U = {
    resizeContent: function () {
        var viewport = U.getWindowSize();
        var h = (viewport.height - $('topHolder').cumulativeOffset()[1] -40);
        if(h < 350)
            h = 350;

        $('content').setStyle({ height: h+'px' });
        $$('.groups').each(function(item) { 
            item.setStyle({ height: (h-50)+'px' }) 
        });
        $('photoGrid').setStyle({ height: ($('groups').getHeight()-$('albumHeader').getHeight()-40)+'px' });
        Photos.updateView();
        
        $$('.albums').each(function(albumdiv) { 
            var subgroup = $(albumdiv.id.replace('groupAlbums_', 'subgroup_'));
            albumdiv.setStyle({ height: ($('groups').getHeight()-(subgroup.visible()?subgroup.getHeight():0)-10)+'px' });
        });
    },
    getWindowSize: function() {

        var width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
        var height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
        
        return { width: width, height: height };
    }
};
// Feed URL generator
var F = {
    l: 'MalNivek.bbs2',
    base: 'https://picasaweb.google.com/data/feed/api/user/MalNivek.bbs2',
    fields: '&fields=entry(title,summary,link,gphoto:id,gphoto:albumid,gphoto:numphotos,media:group/media:thumbnail,gphoto$originalvideo)',
    fields: '',
    // get albums
    g: function() {
        return this.base + '?kind=album&alt=json&callback=groupCallback&thumbsize=160c'+this.fields;
    },
    p: function(pid) {
        return this.base + '/albumid/' + pid +'?kind=photo,tag&alt=json&callback=photoCallback&thumbsize=160c,32u'+this.fields;
    }
};
var TouchHandler = {
    firstTime: true,
    startPos: [ 0, 0 ],
    endPos: [ 0, 0 ],
    bound: [ 0, 0, 0, 0],
    init: function(event) {
        if(this.firstTime) {
            this.firstTime = false;
            alert("Looks like you are on a touch device, you can swipe to prev/next photo!");
        }
    
        var touch = event.targetTouches[0];
        this.startPos = [ touch.pageX, touch.pageY ];
    },
    update: function(event) {

        var touch = event.targetTouches[0];
        this.bound = [ 
            (touch.pageX < this.bound[0])?touch.pageX:this.bound[0], 
            (touch.pageY < this.bound[1])?touch.pageY:this.bound[1],
            (touch.pageX > this.bound[2])?touch.pageX:this.bound[2],
            (touch.pageY > this.bound[3])?touch.pageY:this.bound[3]
        ];
        event.stop();
    },
    end: function(event) {
        var touch = event.changedTouches[0];
        this.endPos = [ touch.pageX, touch.pageY ];
        
        var midX = (this.bound[0]+this.bound[2])/2;
        
        var viewport = U.getWindowSize();
        
        // if the swipe is at least half of the screen or 200px
        var swipeLimit = Math.min(200, viewport.width/2);
        if(Math.abs(this.startPos[0] - this.endPos[0]) > swipeLimit) {
            // S -> E
            if(this.startPos[0] < (this.bound[0]+this.bound[2])/2 && 
                this.endPos[0] > (this.bound[0]+this.bound[2])/2) {
                
                Photos.showPrev();
                   
            } else if(this.startPos[0] > (this.bound[0]+this.bound[2])/2 && 
                this.endPos[0] < (this.bound[0]+this.bound[2])/2) {
                
                Photos.showNext();

            } 
        
        }
    }
};
var Page = {
    canPlayVideo: false,
    currentTab: null,
    currentAlbum: null,
    currentPhoto: null,
    hashContent: null,
    blanker: new Image(),
    setTab: function(tab) {
        this.currentTab = tab;
        this.currentAlbum = null;
        this.currentPhoto = null;
    },
    setAlbum: function(album) {
        this.currentAlbum = album;
        this.currentPhoto = null;
    },
    setPhoto: function(photo) {
        this.currentPhoto = photo;
    },
    makeLink: function() {
        if(this.currentPhoto) {
            if(Photos.currentFilterName)
                location.href = '#t='+this.currentTab+'&a='+this.currentAlbum+'&p='+this.currentPhoto+'&f='+encodeURIComponent(Photos.currentFilterName);
            else
                location.href = '#t='+this.currentTab+'&a='+this.currentAlbum+'&p='+this.currentPhoto;
        } else if(this.currentAlbum) {
            location.href = '#t='+this.currentTab+'&a='+this.currentAlbum;
        } else if(this.currentTab) {
            location.href = '#t='+this.currentTab;
        }
    },
    init: function() {
        this.blanker.src = 'images/blank.png';
        
        $('content').update();
        $('content').insert(new Element('div', { id:'menuSeperator' }).addClassName('cleaner'));
        $('content').insert(new Element('div', { id:'groups' }));

        Groups.groups.keys().each(function(gid) {

            $('menuSeperator').insert({ before: new Element('div', { id: 'tab_'+gid }).addClassName('tab').addClassName('taboff').update(Groups.groups.get(gid).name) });
            
            $('groups').insert(new Element('div', { id: 'group_'+gid }).addClassName('groups').hide()
                .insert(new Element('div', { id: 'subgroup_'+gid }).addClassName('subgroups'))
                .insert(new Element('div', { id: 'groupAlbums_'+gid }).addClassName('albums')));
                
        }.bind(this));
        
        $('groups').insert(new Element('div', { id: 'photos' }).addClassName('groups').hide()
            .insert(new Element('div', { id: 'albumHeader' })
                .insert(new Element('div')
                    .insert(new Element('span', { id: 'albumTitle' }))
                    .insert(new Element('span', { id: 'albumItems' })))
                .insert(new Element('div')
                    .insert(new Element('span', { id: 'albumDesc' }))))
            .insert(new Element('div', { id: 'tags' }))
            .insert(new Element('div', { id: 'photoGrid' })));

        
        $(document.body).insert(new Element('div', { id:'photoViewer' }).hide()
            .insert(new Element('div', { id: 'pictureArea' })
                .insert(new Element('div', { id: 'pictureFrame' })
                    .insert(new Element('img', { id: 'thePic', src: Page.blanker.src }))
                    .insert(new Element('div', { id: 'theVideo' }))
                    .insert(new Element('div', { id: 'theDesc' }))
                    )
                .insert(new Element('div', { id: 'navPane' })
                    .insert(new Element('a', { id: 'navLeft' }).addClassName('nav').addClassName('btn').update('⇦ prev'))
                    .insert(new Element('a', { id: 'navRight' }).addClassName('nav').addClassName('btn').update('next ⇨')))
                .insert(new Element('div', { id: 'infoPane' }))
            ));
        
        Event.observe(window, 'resize', U.resizeContent);
        
        this.canPlayVideo = !!document.createElement('video').canPlayType;
        
        Groups.init();
        
        

    },
    blackout: function() {
        var cover = new Element('div', { id: 'cover' }).addClassName('cover').setOpacity(0.8);
        var coverCloseBtn = new Element('div', { id: 'coverClose' }).addClassName('coverCloseBtn').addClassName('btn').update('x Close');
        

        $(document.body).insert(cover);
        $(document.body).insert(coverCloseBtn);
        
        coverCloseBtn.observe('click', this.unblackout.bind(this));
        
        var touchPane = new Element('div', { id: 'touchPane' }).addClassName('touchPane');
        $(document.body).insert(touchPane);
        $('touchPane').observe('touchstart', TouchHandler.init.bind(TouchHandler));
        $('touchPane').observe('touchmove', TouchHandler.update.bind(TouchHandler));
        $('touchPane').observe('touchend', TouchHandler.end.bind(TouchHandler));
        
      //  cover.observe('click', this.unblackout.bind(this));
    },
    unblackout: function() {
        $$('.cover').invoke('remove');
        $$('.coverCloseBtn').invoke('remove');
        $('touchPane').stopObserving();
        $$('.touchPane').invoke('remove');
        Photos.hidePhoto();
        
    }
    
};
var Groups = {
    groups: null,
    subgroups: $H(),
    albums: $H(),
    gdataMap: $H(),
    prepare: function(groups) {

        this.groups = $H(groups);
        
        this.groups.keys().each(function(gid) {
            var tmpgroup = [];
            this.groups.get(gid).albums.each(function(album) {
            
                this.gdataMap.set(album.picasaId, true);
                var subgroupexists = false;
                tmpgroup.each(function(item) {
                    if(item == album.group)
                        subgroupexists = true;
                });
                if(!subgroupexists)
                    tmpgroup.push(album.group);
                    
            }.bind(this));
            
            this.subgroups.set(gid, tmpgroup);

        }.bind(this));

    },
    init: function() {
    
        $(document.body).insert(new Element('script', { src: F.g() }));
        
    },
    setup: function(data) {
        data.feed.entry.each(function(gphotoEntry) {
            if(this.gdataMap.get(gphotoEntry.gphoto$id.$t))
                this.gdataMap.set(gphotoEntry.gphoto$id.$t, gphotoEntry);
        }.bind(this));
        
        this.groups.keys().each(function(gid) {
            $('tab_'+gid).observe('click', this.clickload.bind(this, gid));
        }.bind(this));

        var transportOK = false;
        if(location.hash.length > 1) {
            Page.hashContent = $H();
            location.hash.substr(1).split('&').each(function(param) {
                var eq = param.indexOf('=');
                if(eq > 0) {
                    Page.hashContent.set(param.substr(0,eq), param.substr(eq+1));
                }
            });
            
            var theTab = Page.hashContent.get('t');
            if(this.load(theTab)) {
                transportOK = true;
                var theAlbum = this.albums.get(theTab);
                if(theAlbum)
                    theAlbum.load(Page.hashContent.get('a'));
 
            }
            
        } 
        
        if(!transportOK) {
            this.load('t');        
        }
        
         
    },
    clickload: function(group) {
        this.load(group);
        Page.makeLink();
    },
    load: function(group) {
        if(!group || !this.groups.get(group)) {
            return false;
        }
        Page.setTab(group);
        if(!this.albums.get(group)) {
            this.albums.set(group, new Album(group, this.groups.get(group)));
        }
        $$('.groups').invoke('hide');
        $$('.tab').invoke('removeClassName', 'tabon');
        $('tab_'+group).addClassName('tabon');
        $('group_'+group).show();
        
        var thisalbum = this.albums.get(group);
        if(thisalbum.currentSubgroup)
            thisalbum.showSubgroup(thisalbum.currentSubgroup);
        else
            thisalbum.showSubgroup(Groups.subgroups.get(group)[0]);
        
        U.resizeContent();
        return true;
    },
    getThumbURL: function(picasaId) {
        return this.gdataMap.get(picasaId).media$group.media$thumbnail[0].url;
    },
    getPhotoCount: function(picasaId) {
        return this.gdataMap.get(picasaId).gphoto$numphotos.$t;
    },
    getTitle: function(picasaId) {
        return this.gdataMap.get(picasaId).title.$t;
    },
    getDesc: function(picasaId) {
        return this.gdataMap.get(picasaId).summary.$t;
    },
    hideAll: function() {
        $$('.groups').invoke('hide');
    }
};

var Album = Class.create({
    groupId: null,
    group: null,
    currentSubgroup: null,
    subgroupMap: $H(),
    initialize: function (groupId, group) {

        this.groupId = groupId;
        this.group = group;
        
        Groups.subgroups.get(groupId).each(function(subgroup) {
            var subgroupswitch = new Element('div', { id: 'g_'+this.groupId+'_'+subgroup }).update(subgroup).addClassName('subgroup');
            $('subgroup_'+this.groupId).insert(subgroupswitch);
            subgroupswitch.observe('click', this.showSubgroup.bind(this, subgroup));
        }.bind(this));
        $('subgroup_'+this.groupId).insert(new Element('div').addClassName('cleaner'));
        if(Groups.subgroups.get(groupId).length <= 1) {
            $('subgroup_'+this.groupId).hide();
        }
        
        this.group.albums.each(function(album) {

            var albumDiv = new Element('div', { id: 'album_'+this.groupId+'_'+album.picasaId }).addClassName('album').addClassName('sg_'+album.group).hide()
                                .insert(new Element('img', { src: Groups.getThumbURL(album.picasaId), width: 160, height: 160 }))
                                .insert(new Element('div').addClassName('info')
                                    .insert(new Element('div').update(Groups.getTitle(album.picasaId)))
                                    .insert(Groups.getPhotoCount(album.picasaId) + ' items'));
                                    
            this.subgroupMap.set(album.picasaId, album.group);
            
            $('groupAlbums_'+this.groupId).insert(albumDiv);
            
            albumDiv.observe('click', this.clickload.bind(this, album.picasaId));
            
        }.bind(this));
        
        $('group_'+this.groupId).show()
        
        this.showSubgroup(Groups.subgroups.get(groupId)[0]);
        
        U.resizeContent();
    },
    showSubgroup: function(subgroup) {
    
        this.currentSubgroup = subgroup;
        
        $$('.album').invoke('hide');
        $$('.sg_'+subgroup).invoke('show');
        
        $$('.subgroup').invoke('removeClassName', 'subgroupon');
        $('g_'+this.groupId+'_'+subgroup).addClassName('subgroupon');
        
    },
    clickload: function(picasaId) {
    
        this.load(picasaId);
        Page.makeLink();
    },
    load: function(picasaId) {
        if(!picasaId || this.group.albums.all(function(album) { return (album.picasaId != picasaId); })) {
            return false;
        }
        
        Page.setAlbum(picasaId);
        this.showSubgroup(this.subgroupMap.get(picasaId));
        
        Groups.hideAll();
        $('photos').show();
        $('tags').hide();
        $('albumTitle').update(Groups.getTitle(picasaId));
        $('albumDesc').update(Groups.getDesc(picasaId));
        $('albumItems').update(Groups.getPhotoCount(picasaId) + ' items');
        
        $('photoGrid').update();
        $(document.body).insert(new Element('script', { src: F.p(picasaId) }));
        
        U.resizeContent();
    }
});

var Photos = {
    photoData: null,
    currentPhoto: null,
    currentPhotoIdx: 0,
    currentVideo: null,
    preloads: $H(),
    currentFilter: null,
    currentFilterName: null,
    populateGrid: function(data) {
        this.photoData = data;
        this.preloads = $H();
        var imgIdx = 0;
        var tagIdx = 1;
        var tags = $H();
        
        $('tags').hide();
        $('tags').childElements().invoke('remove');
        
        // first process tags
        this.photoData.feed.entry.each(function(item) {
            if(!item.media$group) {
                // This is a tag!
                tags.set(item.title.$t, tagIdx);
                tagIdx++;
            }
        });
        
        // For deep link..
        var findId = null;
        var filter = null;
        if(Page.hashContent) {
            findId = Page.hashContent.get('p');
            if(Page.hashContent.get('f'))
                filter = decodeURIComponent(Page.hashContent.get('f'));
        }
        
        this.photoData.feed.entry.each(function(item) {
            if(!item.media$group) {
                // This is a tag!
            } else {
                var photoItemDiv = new Element('div', { id: 'photoTV_'+item.gphoto$id.$t }).addClassName('thumbview')
                        .insert(new Element('div')
                            .insert(new Element('img', { id: 'itemthumb_'+imgIdx, src: item.media$group.media$thumbnail[0].url, width: 160, height: 160 }).addClassName('thumb')))
                        .insert(new Element('div').addClassName('photoDesc').update(item.summary.$t));
                
                if(item.media$group.media$keywords.$t) {
                    item.media$group.media$keywords.$t.split(',').each(function(tag) {
                        photoItemDiv.addClassName('tag_'+tags.get(tag.trim()));
                    });
                }
                
                $('photoGrid').insert(photoItemDiv);
                if(findId && findId == item.gphoto$id.$t) {
                    this.initShow(imgIdx);
                    this.show(imgIdx);
                }
                photoItemDiv.observe('click', this.clickInitShow.bind(this, imgIdx));
            }
            
            ++imgIdx;
        }.bind(this));
        
        if(tags.size() > 1) {
            var orderedTags = tags.keys().sortBy(function(tag) { 
                if(tag == 'E2C') 
                    return '.'; 
                else 
                    return tag; 
            });
            
            orderedTags.each(function(tag) {
                var tagToggleBtn = new Element('div', { id: 'fil_'+tags.get(tag) }).update(tag).addClassName('tag');
                $('tags').insert(tagToggleBtn);    
                var thisIdx = tags.get(tag);
                tagToggleBtn.observe('click', function(event) {
                    var tagBtn = event.findElement();
                    if(tagBtn.hasClassName('tagon')) {
                        $$('.thumbview').invoke('show');
                        event.findElement().removeClassName('tagon');
                        this.currentFilter = null;
                        this.currentFilterName = null;
                    } else {
                        $$('.tag').invoke('removeClassName', 'tagon');
                        event.findElement().addClassName('tagon');
                        $$('.thumbview').invoke('hide');
                        $$('.tag_'+thisIdx).invoke('show');
                        this.currentFilter = tagBtn.id.substr(tagBtn.id.indexOf('_')+1);
                        this.currentFilterName = tag;
                    }
                }.bind(this));
            }.bind(this));
            $('tags').show();
        }
        
        // deep link
        if(filter) {
            var filterId = tags.get(filter);
            $('fil_'+filterId).addClassName('tagon');
            $$('.thumbview').invoke('hide');
            $$('.tag_'+filterId).invoke('show');
            this.currentFilter = filterId;
            this.currentFilterName = filter;
        }

        
    },
    clickInitShow: function(imgIdx) {
        this.initShow(imgIdx);
        this.clickShow(imgIdx);
    },
    initShow: function(imgIdx) {
 
        Page.blackout();
        $('navLeft').observe('click', this.showPrev.bind(this));
        $('navRight').observe('click', this.showNext.bind(this));
        $('photoViewer').show();
        document.observe('keydown', function(event) {
            switch(event.keyCode) {
                case Event.KEY_LEFT:
                    this.showPrev();
                    break;
                case Event.KEY_RIGHT:
                    this.showNext();
                    break;
            }
        }.bind(this));
    },
    clickShow: function(imgIdx) {
        this.show(imgIdx);
        Page.makeLink();
    }, 
    show: function(imgIdx) {
//        var x = this.photoData;
   
        Page.setPhoto(this.photoData.feed.entry[imgIdx].gphoto$id.$t);
            
        this.currentPhotoIdx = imgIdx;
        this.currentPhoto = this.photoData.feed.entry[imgIdx];
            
        $('theVideo').childElements().invoke('remove');
        $('thePic').src = Page.blanker.src;
        
        $('theDesc').update(this.currentPhoto.summary.$t); 
        
        $$('#infoPane div').invoke('remove');
        
        if(this.currentPhoto.gphoto$originalvideo) {
        
            $('theVideo').show();
            $('thePic').hide();

            var viewport = document.viewport.getDimensions();
            var availableH = Math.max(viewport.height-150, 1);
            var availableW = Math.max(viewport.width-200, 1);
            
            var videoToShow = null;
            // find the best video to show based on the current viewport
            this.currentPhoto.media$group.media$content.each(function(candidate) {
                if(candidate.medium == 'video' && candidate.width <= availableW && candidate.height <= availableH) {
                    var validchoice = false;
                    if(candidate.type == "application/x-shockwave-flash")
                        validchoice = true;
                    else if(Page.canPlayVideo)
                        validchoice = true;
                        
                    if(validchoice) {
                        if(videoToShow == null)
                            videoToShow = candidate;
                        else  {
                            if(videoToShow.width < candidate.width)
                                videoToShow = candidate;
                            else if(videoToShow.width == candidate.width && candidate.type != "application/x-shockwave-flash") {
                                videoToShow = candidate;
                            }
                        }
                    }
                } 
                    
            });
            
            var pawurl = null;
            var linkid = 0;
            for(; linkid<this.currentPhoto.link.length; ++linkid) {
                if(this.currentPhoto.link[linkid].rel == 'alternate') {
                    pawurl = this.currentPhoto.link[linkid].href;
                    break;
                }
            }
            
            if(videoToShow.type == "application/x-shockwave-flash") {
                $('theVideo').insert(new Element('div', { id: 'swfalt' }).setStyle({
                    width: videoToShow.width+'px',
                    height: videoToShow.height+'px'
                }).update("Trying to load flash video"));

                swfobject.embedSWF('http://video.google.com/googleplayer.swf?videoUrl='+encodeURIComponent(videoToShow.url), 'swfalt', videoToShow.width, videoToShow.height, "10");
            } else {
                var videoElem = new Element('video', { src: videoToShow.url, controls: 'controls' });
                $('theVideo').insert(videoElem);
                
            }
            this.currentVideo = videoToShow;
            
            if(this.currentPhoto.gphoto$originalvideo.duration) {
                var d = this.currentPhoto.gphoto$originalvideo.duration;
                var s = d%60;
                var m = (d-s)/60;
                $('infoPane').insert(new Element('div').update(m+'m'+s+'s'));
            }
            

            if(pawurl) {
                var pwalink = new Element('a', { href: pawurl }).update('click here');
                pwalink.observe('click', function(event) {
                    window.open(event.findElement().href);
                    event.stop();
                    return false;
                });
                $('infoPane').insert(new Element('div').addClassName('infoModel')
                    .insert('This is a video, if you can\'t view it properly, ')
                    .insert(pwalink)
                    .insert(' to view it in PicasaWeb'));
            }

        } else {
            $('theVideo').hide();
            $('thePic').show();
            $('thePic').src = Page.blanker.src;
            var preloadImg = this.preloads.get(imgIdx);
            if(preloadImg)
                $('thePic').src = preloadImg.src;
            else
                $('thePic').src = this.currentPhoto.content.src;
            
            if(this.currentPhoto.exif$tags.exif$model)
                $('infoPane').insert(new Element('div').addClassName('infoModel').update(this.currentPhoto.exif$tags.exif$model.$t));
            if(this.currentPhoto.media$group.media$keywords.$t) {
                this.currentPhoto.media$group.media$keywords.$t.split(',').each(function(tag) {
                    $('infoPane').insert(new Element('div').update(tag.trim()));
                });
            }
            if(this.currentPhoto.exif$tags.exif$model) {
                var ts = new Date(parseInt(this.currentPhoto.gphoto$timestamp.$t));
                $('infoPane').insert(new Element('div').update(
                    ts.getFullYear()+'-'+
                    ('0'+(ts.getMonth()+1)).substr(-2)+'-'+
                    ('0'+ts.getDate()).substr(-2)+' '+
                    ('0'+ts.getHours()).substr(-2)+':'+
                    ('0'+ts.getMinutes()).substr(-2)+':'+
                    ('0'+ts.getSeconds()).substr(-2)));        
            }
            if(this.currentPhoto.exif$tags.exif$iso)
                $('infoPane').insert(new Element('div').update('iso'+this.currentPhoto.exif$tags.exif$iso.$t));
            if(this.currentPhoto.exif$tags.exif$fstop)
                $('infoPane').insert(new Element('div').update('f/'+this.currentPhoto.exif$tags.exif$fstop.$t));
            if(this.currentPhoto.exif$tags.exif$exposure) {
                var exp = parseFloat(this.currentPhoto.exif$tags.exif$exposure.$t);
                if(exp < 0.1) {
                    var r_exp = 1/exp;
                    if(Math.round(r_exp) > 10) {
                        r_exp = Math.round(r_exp/5)*5;
                    } else 
                        r_exp = Math.round(r_exp);
                    exp = '1/'+r_exp;
                }
                $('infoPane').insert(new Element('div').update(exp+'s'));
            }
            if(this.currentPhoto.exif$tags.exif$flash && this.currentPhoto.exif$tags.exif$flash.$t == 'true')
                $('infoPane').insert(new Element('div').update('with flash'));
        }
                
        var nextIdx = this.getNextIdx();
        if(nextIdx >= 0) {
            if(!this.preloads.get(nextIdx)) {
                var preloadImg = new Image();
                preloadImg.src = this.photoData.feed.entry[nextIdx].content.src;
                this.preloads.set(nextIdx, preloadImg);
            }
            $('navRight').removeClassName('disable');
        } else
            $('navRight').addClassName('disable');
            
        var prevIdx = this.getPrevIdx();
        if(prevIdx >= 0) 
            $('navLeft').removeClassName('disable');
        else
            $('navLeft').addClassName('disable');
           
        this.updateView();

    },
    getNextIdx: function() {
        if(this.currentFilter === null) {
            if(this.currentPhotoIdx < this.photoData.feed.gphoto$numphotos.$t-1)
                return this.currentPhotoIdx+1;
            else
                return -1;
        } else {
            var tryIdx = this.currentPhotoIdx+1;
            while(tryIdx < this.photoData.feed.gphoto$numphotos.$t) {
                if($('photoTV_'+this.photoData.feed.entry[tryIdx].gphoto$id.$t).hasClassName('tag_'+this.currentFilter))
                    return tryIdx;
                tryIdx++;
            }
            return -1;
        }
        
    },
    getPrevIdx: function() {
        if(this.currentFilter === null) {
            if(this.currentPhotoIdx > 0)
                return this.currentPhotoIdx-1;
            else
                return -1;
        } else {
            var tryIdx = this.currentPhotoIdx-1;
            while(tryIdx >= 0) {
                if($('photoTV_'+this.photoData.feed.entry[tryIdx].gphoto$id.$t).hasClassName('tag_'+this.currentFilter))
                    return tryIdx;
                tryIdx--;
            }
            return -1;
        }
        
    },
    showNext: function() {
        var nextIdx = this.getNextIdx();
        if(nextIdx >= 0) 
            this.clickShow(nextIdx);
    },
    showPrev: function() {
        var prevIdx = this.getPrevIdx();
        if(prevIdx >= 0) 
            this.clickShow(prevIdx);
    },
    updateView: function() {
    
        if(this.currentPhoto) {
        
            // Scroll down a bit to get rid of the address bar
            window.scrollTo(0, 1);
            
            var viewport = U.getWindowSize();
            var availableH = viewport.height;
            var availableW = viewport.width;
            
            if(availableW < 450) {
                // use a smaller button
                $$('.btn').invoke('addClassName', 'btnsmall');
                $$('#infoPane div').invoke('addClassName', 'small');
            } else {
                $$('.btn').invoke('removeClassName', 'btnsmall');
                $$('#infoPane div').invoke('removeClassName', 'small');
            }
            
            $('navPane').setStyle( { width: availableW-$('coverClose').getWidth()-10+'px' });
            $('touchPane').setStyle( { height: availableH - $('navPane').getHeight()-5+'px' });
            // Next determine the scheme to use
            var scheme = 'h';
            if(availableH > availableW) {
                var scheme = 'v';
            }

            

            if(scheme == 'h') {
                availableW = Math.max(viewport.width-$('infoPane').getWidth()-35, 1);
            } else {
                availableW = Math.max(viewport.width-35, 1);
            }
            
            
            if(scheme == 'h') {
                availableH = Math.max(viewport.height-$('coverClose').getHeight()-$('theDesc').getHeight()-50, 1);
   
            } else {

                $('infoPane').setStyle( { 
                    top: '10px',
                    left: '20px',
                    width: availableW-50+'px'
                });
                $$('#infoPane div').each(function(infoDiv) {
                    infoDiv.setStyle({
                        'float': 'left'
                    });
                });
                
                availableH = Math.max(viewport.height-$('coverClose').getHeight()-$('theDesc').getHeight()-$('infoPane').getHeight()-50, 1);
   
            }

             
            $('pictureArea').setStyle({ width: availableW+20+'px' });

      //      $('infoPane').setStyle( { height: availableH-100+'px' });

            var picH = 0;
            var picW = 0;
            if(this.currentPhoto.gphoto$originalvideo) {
                picH = this.currentVideo.height;
                picW = this.currentVideo.width;
            } else {
                
                var picH = parseInt(this.currentPhoto.gphoto$height.$t);
                var picW = parseInt(this.currentPhoto.gphoto$width.$t);
                
                if(picH > availableH || picW > availableW) {
                    var tryH = availableW * picH / picW;
                    var tryW = availableW;
                    if(tryH > availableH) {
                        tryH = availableH;
                        tryW = availableH * picW / picH;
                    }
                    picW = tryW;
                    picH = tryH;

                }
                $('thePic').width = picW;
                $('thePic').height = picH;
            }
            
            $('pictureFrame').setStyle( { width: picW+'px' });
            
            if(scheme == 'h') {
                $('infoPane').setStyle( { 
                    top: '20px',
                    left: $('pictureFrame').cumulativeOffset()[0]+$('pictureFrame').getWidth()+5+'px',
                    width: '150px'
                });
                $$('#infoPane > div').each(function(infoDiv) {
                    infoDiv.setStyle({
                        'float': 'none'
                    });
                });
            } else {

                $('infoPane').setStyle( { 
                    top: $('pictureFrame').cumulativeOffset()[1]+$('pictureFrame').getHeight()+5+'px',
                    left: '20px',
                    width: picW+'px'
                });
                $$('#infoPane div').each(function(infoDiv) {
                    infoDiv.setStyle({
                        'float': 'left'
                    });
                });
            }

        }
    },
    hidePhoto: function() {
        this.currentPhoto = null;
        $('photoViewer').hide();
        $('navLeft').stopObserving();
        $('navRight').stopObserving();
        document.stopObserving('keydown');
        Page.setPhoto(null);
        Page.makeLink();
    }
};

