/* Copyright 2009 Xsevo */
var xsGallery = {
    ArticleId:0,Photo:{},PhotoId:0,URLTitle:'',LastId:0,LoadedId:0,Photos:[],PhotoCount:0,Loaded:false,
    ScrollIdx:0,ScrollCount:0,ScrollWidth:0,NoAutoHide:true,LoadImg:null,PhotoBoxWidth:0,PhotoBoxHeight:0,
    ShowBg:true,BoxId:'xs-gallery', ClassName:'xs-gallery',ImgPrefix:'photo/g-',SlidePrefix:'photo/m-',
    GalleryInlineClass:'xs',
    ScrollSpacing:1,
    click: function(el,d,a) {
        if (a) this.ArticleId = a;
        if (el && !el.href) {
            var c = el.getElementsByTagName('a');
            if (c) el = c[0];            
        }
        this.LastId = this.PhotoId;
        this.El = el?el:0;
        this.Dir = d?d:0;
        
        if (!this.El) { 
            if (!this.Loaded) { this.load(); } else { this.display(); }
            return false;
        }
        
        if (this.parseURL(this.El.href) && this.ArticleId) {
            if (!this.Loaded) { this.load(); return false; } 
            this.display();
            return false;
            
        }
        return true;        
    },
    load: function() {
        var query = {Act:'load', Ret:'load'};
        new Ajax.Request(xs.path+'id/'+this.ArticleId+'//gal/', {parameters:$H(query).toQueryString(), onSuccess:this.jsReturn.bind(this)});
    },
    load_ret: function(response) {
        if (response.Photos) this.Photos = response.Photos;
        this.setIndices();
        this.Loaded = true;
        this.display();
    },
    setIndices: function(id) {
        this.PhotoCount = this.Photos.length;
        for (var i=0; i<this.PhotoCount;i++) this.Photos[i].Idx = i;
    },
    display: function() {  
        if (this.El) {
            this.parseURL(this.El.href);
            if (!this.setPhoto()) return;
        } else {
            if (!this.selPhoto(this.Dir)) return;
        }
        if (!this.Visible) this.prep();     
        this.loadPhoto();
        if (!this.Visible) this.show();
    },
    parseURL: function(u) {
        if (!u) return false;
        if (u.charAt(u.length-1) != '/') u += '/';
        var a = u.split('/').reverse();
        
        try {            
            if (a[3] != 'photo') return false;
            
            this.PhotoId = parseInt(a[2]);
            this.URLTitle = a[4];
            this.ArticleId = parseInt(a[5]);
        } catch(e) {
            return false;
        }
        return true;
    },
    prep: function() {
        if (!this._init()) this.setContents();
        this.prepBox();
    },
    show: function() {
        var size = this.Box.getDimensions();
        var wsize = xsUtil.getWindowSize();
        var hover_left = Math.round((wsize.width - size.width) / 2);
        var hover_top = Math.round((wsize.height - size.height) / 2) + (document.documentElement.scrollTop || document.body.scrollTop);
        this.showBox(hover_left > 0 ? hover_left : 0, hover_top > 0 ? hover_top: 0);        
    },    
    selPhoto: function(d) {
        var idx = 0;
        if (this.Photo && d) {
            idx = this.Photo.Idx;
            if (d == 1) {
                if (idx>0) { idx--; } else { return false; }
            } else if (d == 2) {
                if (idx<(this.PhotoCount-1)) { idx++ } else { return false; }
            } 
        }
        return this.setPhoto(idx, 'Idx');
    },
    setPhoto: function(v, field) {
        if (!field) v = v || this.PhotoId;
        field = field || 'Id';
        var photo = this.getPhoto(v, field);
        if (photo) {
            this.Photo = photo;
            this.PhotoId = this.Photo.Id;
            return true;
        } else {
            return false;
        }
    },
    getPhoto: function(v, field) {
        field = field || 'Id';
        for (var i=0; i<this.PhotoCount;i++) {
            var p = this.Photos[i];
            if (p[field] == v) return p;
        }
        return {};
    },
    loadPhoto: function() {
        if (this.Photo.Id == this.LoadedId) return false;
        
        if (!this.LoadImg) this.LoadImg = new Image();
        
        this.LoadImg.onload = this.photoOnload.bind(this);
        this.setStatus(true);
        this.LoadImg.src = xs.path+this.ImgPrefix+this.Photo.PhotoFile;

    },
    setSelected: function() {
        if (this.LastId) Element.removeClassName($('Gal_'+this.LastId), 'xs-gallery-sel');
        if (this.PhotoId) Element.addClassName($('Gal_'+this.PhotoId), 'xs-gallery-sel');
    },
    photoOnload: function() {
        if (!this.ScrollWidth) this.setSizing();
        
        this.scroll();   
        this.setSelected();
        
        var w = this.LoadImg.width;
        var h = this.LoadImg.height;

        if (((w>0) && (h>0)) && ((w > this.PhotoBoxWidth) || (h > this.PhotoBoxHeight))) {
            var ar = w/h;
            if (ar > 0) {
                if (ar > this.PhotoBoxAspect) {
                    w = this.PhotoBoxWidth;
                    h = parseInt(Math.floor(this.PhotoBoxWidth/ar));
                } else {
                    h = this.PhotoBoxHeight;
                    w = parseInt(Math.floor(this.PhotoBoxHeight*ar));
                }
            }
        }
            
        this.PhotoCell.setOpacity(0.0);
    
        var size = {width:w+'px', height:h+'px'};
        this.PhotoCell.setStyle(size);
        this.PhotoCell.innerHTML = '<a target="_blank" title="View full size" href="'+xs.path+'id/'+this.ArticleId+'/'+this.URLTitle+'/photo/'+this.Photo.Id+'/'+(this.Photo.URLTitle?this.Photo.URLTitle+'/':'')+'"><img id="PhotoEl" src="'+xs.path+this.ImgPrefix+this.Photo.PhotoFile+'" /></a>';
        $('PhotoEl').setStyle(size);

        this.TitleBox.innerHTML = this.Photo.Title;
        this.CaptionBox.innerHTML = this.Photo.Caption;
        this.Label.innerHTML = '<a class="arr" href="#" onclick="return xsGallery.click(0,1);" title="Previous Photo">&laquo;</a> <b>'+(this.Photo.Idx+1)+'</b> of <b>'+this.PhotoCount+'</b> <a class="arr" href="#" onclick="return xsGallery.click(0,2);" title="Next Photo">&raquo;</a>';
        this.setStatus(false);
        
        new Effect.Opacity(this.PhotoCell, {duration:0.3, from:0.0, to:1}); 
        this.LoadedId = this.Photo.Id;
    },
    setContents: function() {
        var buf = '<div class="xs-gallery-main-box"><div class="xs-gallery-photo-box" id="GalleryPhotoBox"><table class="xs-gallery-tbl" cellspacing="0"><tr><td class="xs-gallery-tbl-cell"><div class="xs-gallery-photo-cell" id="GalleryPhotoCell"></div></td></tr></table></div><div class="xs-gallery-caption-box"><div class="xs-gallery-caption-title-box" id="GalleryTitleBox"></div><div class="xs-gallery-caption-inner-box" id="GalleryCaptionBox"></div><div id="GalleryStatus" class="xs-gallery-status"></div><div class="xs-gallery-caption-footer"><div class="xs-gallery-label" id="GalleryLabel"></div><div id="GalleryCmd" class="xs-gallery-cmd"><a href="#" onclick="return xsGallery.hide();" title="Close Gallery">[ close ]</a></div></div></div></div><div class="xs-gallery-control-box"><a href="#" onclick="return xsGallery.scroll(1);" class="xs-gallery-left" title="Scroll Left"></a><div id="GallerySlideBox" class="xs-gallery-slide-box"><table cellspacing="'+this.ScrollSpacing+'" id="GallerySlides" class="xs-gallery-slides"><tr>';
        this.Photos.each(function(p){
            buf += '<td id="Gal_'+p.Id+'" onclick="return xsGallery.click(this);"><a onclick="return false;" href="'+xs.path+'id/'+this.ArticleId+'/'+this.URLTitle+'/photo/'+p.Id+'/'+p.URLTitle+'/"><img src="'+xs.path+this.SlidePrefix+p.PhotoFile+'" /></a><div></div></td>';
        }.bind(this));
        buf += '</tr></table></div><a href="#" onclick="return xsGallery.scroll(2);" class="xs-gallery-right" title="Scroll Right"></a></div>';
        
        this.Box.innerHTML = buf;
        this.PhotoCell = $('GalleryPhotoCell');
        this.PhotoBox = $('GalleryPhotoBox');
        this.TitleBox = $('GalleryTitleBox');
        this.CaptionBox = $('GalleryCaptionBox');
        this.Status = $('GalleryStatus');
        this.Label = $('GalleryLabel');
        this.Slides = $('GallerySlides');
        this.SlideBox = $('GallerySlideBox');
        
        Event.observe(document, 'keydown', this.keydown.bind(this));      
    },
    setSizing: function() {
        var sbw = this.SlideBox.getDimensions().width;
        
        if (this.PhotoCount > 0) {
            var p_id = this.Photo.Id;
            var p_el = $('Gal_'+p_id);
            if (p_el) {
                var w = p_el.getDimensions().width;
                this.ScrollWidth = w+this.ScrollSpacing;
            }
            if (this.ScrollWidth > 0) this.ScrollCount = parseInt(Math.floor(sbw / this.ScrollWidth));
        }    
        try {
            var pbs = this.PhotoBox.getDimensions();
            this.PhotoBoxWidth = pbs.width;
            this.PhotoBoxHeight = pbs.height;
            this.PhotoBoxAspect = (this.PhotoBoxWidth>0) && (this.PhotoBoxHeight>0) ? this.PhotoBoxWidth / this.PhotoBoxHeight : 1;
        } catch  (e) { xsJSError(e); }
    },
    keydown: function(event) {
        var key = event.keyCode;
        if (key == 27) {
            this.hide();
        } else if (key == 37) {
            this.click(0,1);
        } else if (key == 39) {
            this.click(0,2);
        }
        
    },
    setStatus: function(f) {
        this.Status.setStyle({visibility:f?'visible':'hidden'});        
    },
    scroll: function(f) {
        var sc = this.ScrollCount;
        var os = this.ScrollIdx;

        if (f) {
            this.ScrollIdx += f==1?-sc:sc;            
        } else {
            if (this.Photo.Idx < os) {
                this.ScrollIdx = this.Photo.Idx;
            } else if (this.Photo.Idx > (os + (sc-1))) {
                this.ScrollIdx = this.Photo.Idx - (sc-1);
            }
        }
        
        var pidx = this.ScrollIdx;
        if (this.ScrollIdx > (this.PhotoCount-sc)) this.ScrollIdx = this.PhotoCount-sc;
        if ((this.PhotoCount > sc) && this.ScrollIdx > (this.PhotoCount - sc)) this.ScrollIdx = this.PhotoCount - sc;
        if (this.ScrollIdx < 0) this.ScrollIdx = 0;
        if (os != this.ScrollIdx) new Effect.Move(this.Slides, {x:-(this.ScrollWidth * this.ScrollIdx), duration: 0.5, mode:'absolute'});
        return false;
    },    
    jsReturn: function(req_obj, obj) {
        try {
            var response = obj?obj:eval('('+req_obj.responseText+')');
        } catch (e) { if (req_obj.responseText) { xsJSError(e); } return; }
        try {
            if (!isUndefined(response.Error)) {
                alert(response.Error);
            } else {
                if (!isUndefined(response.Message)) alert(response.Message);
                var ret = response.Ret;
                if (ret && this[ret+'_ret']) this[ret+'_ret'](response);
            } 
        } catch (e) { }
    },
    setEvents: function(parent, target) {
        xs.register(function() {                
            var el = $(parent || document);
            target = target || this.GalleryInlineClass;
            var links = el.getElementsByTagName('a');
            for (var i=0; i<links.length;i++) {
                var node = links.item(i);
                if (node.className != target) return;
                node.onclick = this.click.bind(this,node);
            }
        }.bind(this));
    }
};
Object.extend(xsGallery, xsHoverBase);