/**
 * A gallery/nav system
 *
 * This gallery contains/requires an area for thumbs and a main image
 * area. It collects image information via AJAX/JSON. It has the capability
 * to browse data 1 or 2 levels deep.
 *
 * Single level:
 * -------------
 * Operation: - hovering mouse over either end of thumb area will scroll thumbs
 *            - click on thumb will load full image into main image area
 *            - click on main image nav will move to prev/next thumb
 * Data:
 * JSON = [
 * {'thumb' => thumb_url, 'full' => full_url, 'text' => 'descriptive text'},
 * ... 
 * ]
 *
 * 2 level:
 * --------
 * Operation: - hovering mouse over either end of thumb area will scroll thumbs
 *            - click on thumb will load that gallery
 *            - click on main image nav will move to prev/next image in 
 *              selected gallery
 *
 * JSON = [
 * {'thumb' => thumb_url,
 *   'text' => 'descriptive text',
 *   'gallery' => [
 *      {'thumb' => thumb_url, 'full' => full_url, 'text' => 'descriptive text'},
 *     ...
 *   ]
 * },
 * ...
 * ]
 *
 * TODO:
 * - decide what to do with the auto func in the case of galleries
 * - need to test hybrid gallery/flat JSON
 * 
 * Version 0.9
 * Nov 13, 2008
 * Copyright (c) 2008 Barking Dog Studios (http://barkingdogstudios.com)
 * Authors: J. Knight
 * Licensed under the GPL licenses.
 * http://www.gnu.org/licenses/gpl.txt
 *
 * Note: This was loosly based on code by Muchael Leigeber
 * (http://www.leigeber.com/2008/05/ajax-image-gallery-slideshow/). It was
 * pretty much completly rewritten to use jQuery, handle galleries, 
 * use JSON/AJAX, etc.
 **/

// grab the BDS namespace
//var BDS = BDS || {};

var BDS = window.BDS || {};

/* this thing requires jquery */
BDS.gallery = function() 
{
    
    // config defaults. these can be overridden in the load: or init: method
    var config = {
        // url to retrieve the JSON data
        url: 'gallery.php?get_thumbsh=1',
        // id of the thumb div
        thumbid: 'thumbs',
        // id of the image div
        imgid: 'image',
        // id of the thumb area div
        thumbareaid: 'thumbarea',
        // tooltip name
        tooltipid: 'tooltip',
        // autoplay
        auto: false,
        // autoplay delay in seconds
        autoDelay: 5,
        // fade in/out speed in seconds
        fadeSpeed: 0.5,
        // thumb scroll speed
        scrollSpeed: 3,
        // this is not very useful
        scrollTimer: 1,
        // toggle the nav when hover over main image
        toggleNav: true,
        // xtooltips
        xtooltips: true,
	    // the thumb to load initially
		initThumb: 1
    };
    // the thumb div
    var thumbArea;
    // the big image
    var imageArea;
    // internet exploder flag
    var isIE = false;
    // the current large image
    var curImg = null;
    // index into the thumbs
    var thumbNdx = 0;
    // if we are doing a gallery, this is our offset into that
    var galNdx = 0;    
    // are we in a gallery?
    var inGal = false;
    // the image data references
    var imgData = null;

    // these are ugly and need to be encapsulated at some point
    var bxs,bxe,fxs,fxe,ys,ye,xp,yp;
    var xp,yp = 0;
    
    return {    
        
        // init configuration elements
        init: function( opts ) {
			jQuery.extend( config, opts );
	        isIE = document.all ? true : false;
        },
        
        // load thumbs via json
        load: function( opts ) {
            
            // check that we have run config already
            if( opts ) {
                BDS.gallery.init( opts );
            }
            // get the thumbs div
            var thumbs = $('#'+config.thumbid).get(0);
            if( thumbs != null ) {
                // nuke it if it's already there
                $(thumbs).remove();
            }

            // create the thumbs div
            thumbs = $(document.createElement('ul'));
            thumbs.attr('id', config.thumbid);
            
            // get the imgData from JSON
			
            $.getJSON(config.url, function(data) {
                BDS.gallery.imgData = data;
                for( var i = 0; i < data.length; i++ ) {
                    var img = $(document.createElement('img'));
                    img.attr('src', data[i].thumb);
                    img.attr('title', data[i].text);
                    img.css('opacity', 0.5);
                    var li = $(document.createElement('li'));
                    li.attr('tvalue', i + 1);
                    li.append(img);
                    thumbs.append(li);
                    if( config.xtooltips ) {
                        name = 'tooltip';
                        $("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+data[i].text+"</p></div>");
                    }
                }
				
				
                // add the thumbs to the thumbarea
                $('#'+config.thumbareaid).append(thumbs);
                
                // if we are hiding the nav
                if( config.toggleNav) {
                    // hook up the mouse event for the main image
                    $('#'+config.imgid).mouseover(function(){
                        BDS.gallery.togglenav( true );
                    });
                    $('#'+config.imgid).mouseout(function(){
                        BDS.gallery.togglenav( false );                    
                    });
                    BDS.gallery.togglenav(false);
                }
                // fancy tooltips
                if( config.xtooltips ) {
                    $('#' + config.thumbid + ' li img').each(function(i) {
                        name = 'tooltip';
                        $("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
                        
                		var my_tooltip = $("#"+name+i);

                		$(this).removeAttr("title").mouseover(function(){
                				my_tooltip.css({opacity:0.8, display:"none"}).fadeIn(400);
                		}).mousemove(function(kmouse){
                				my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
                		}).mouseout(function(){
                				my_tooltip.fadeOut(100);
                		});
                    });
                }
                BDS.gallery.show();
				// sanity
				if( config.initThumb < 1 ) config.initThumb = 1;
				if( config.initThumb >  BDS.gallery.imgData.length ) config.initThumb = BDS.gallery.imgData.length;
            	BDS.gallery.showGallery(config.initThumb);
            });
			
        },

        togglenav: function( show ) {
            // hide the nav
            $('#'+config.imgid+ ' a').each(function(ndx) {
                if( show ) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        },
                
        // start the show
        show: function() {
                                            
            thumbArea = $('#' + config.thumbid).get(0);
            imageArea = $('#' + config.imgid).get(0);

            document.onmousemove = this.pos;
            window.onresize = function() {
                setTimeout("BDS.gallery.calc_limits()", 500);
            };
            
            this.thumbNdx = 0;
            this.galNdx = 0;
            ys = this.toppos(thumbArea);
            ye = ys + thumbArea.offsetHeight;
            
            // add click to each thumb
            $('#' + config.thumbid + ' li').each(function(ndx) {
               val = $(this).attr('tvalue');
               $(this).unbind('click');
               $(this).click(function(){
                  BDS.gallery.getimg($(this).attr('tvalue'),false); 
               });
               if( ndx == 0) BDS.gallery.getimg(val,false);
            });
            
            BDS.gallery.calc_limits();
        },
                
        // set the current thumb opacity
        setThumbsView: function( id ) {
            $('#'+config.thumbid + ' li img').each(function(ndx) {
                var timg = $(this);
                if(timg.parent().attr('tvalue') == id) {
					timg.addClass('selected');
                    timg.css('opacity', 1.0 );
                } else {
					timg.removeClass('selected');
                    timg.css('opacity', 0.5 );                        
                }
            });            
        },
            
        // display the main image
        getimg: function( iid, mainnav) {
            
            if (config.auto) {
                clearTimeout(imageArea.timer);
            }
            
            var imgSrc = null;
            var imgText = '';
            

            if( mainnav ) {
                // user clicked nav button
                //console.log('nav clicked');
                if( this.imgData[this.thumbNdx].gallery ) {
                    this.inGal = true;
                    this.galNdx = iid - 1;
                } else {
                    this.inGal = false;
                    this.galNdx = 0;
                    this.thumbNdx = iid - 1;                    
                    this.setThumbsView( iid );
                }
            } else {
                // user clicked thumb
                //console.log('thumb clicked');
                this.galNdx = 0;
				this.thumbNdx = (iid - 1);                
                this.setThumbsView( iid );
            }
            

            // get the img src and text/depending on our mode
            if( this.imgData[this.thumbNdx].gallery ) {
                imgSrc = this.imgData[this.thumbNdx].gallery[this.galNdx].full;
                imgText = this.imgData[this.thumbNdx].gallery[this.galNdx].text;
            } else {
                imgSrc = this.imgData[this.thumbNdx].full;
                imgText = this.imgData[this.thumbNdx].text;
            }

            //console.log( 'thumb: ' + this.thumbNdx + " - gal: " + this.galNdx );
            
            if (this.curImg != null) {
                // fade the image out and remove it
                $('#'+config.imgid+' img').fadeOut('slow').remove();
            }
            
            // grab the current image
            var img = $('#'+config.imgid+' img');
            if( $(img).get(0) == null ) {
                // no image so create a new one and load it up
                //img = $(document.createElement('img'));
                img = new Image();
                $(img).attr('ivalue', iid);
                $(img).attr('src', imgSrc );//this.imgData[id-1].full);
                //img.attr('title', imgText );
                $(img).hide();
                $('#'+config.imgid).append( img );
            } 
             
            $(img).fadeIn('slow');
			
			// bluenorth specific issue
			
			if( this.imgData[this.thumbNdx].gallery ) {
				$('#body_blurb').html(this.imgData[this.thumbNdx].gallery[this.galNdx].body );
			}
            
            
            this.curImg = $('#'+config.imgid+' img').get(0); 
            if( config.auto ) {
                this.auto();
            }           
        },
    
        // do some navigation
        nav: function(d) {
            var iid = 1;
            if( this.curImg != null ) {
                iid = parseInt($(this.curImg).attr('ivalue'));
            }
            var offs = iid + d;
            len = this.imgData.length;
            if( this.inGal ) {
                len = this.imgData[this.thumbNdx].gallery.length;
            }
            if( offs < 1 ) offs = len;
            if( offs > len ) offs = 1;
            this.getimg( offs, true );
        },
    
        // prev image
        prev: function() {
          this.nav(-1);  
        },
    
        // next image
        next: function() {
          this.nav(1);  
        },
    
        // set the auto timer
        auto: function() {
            imageArea.timer = setInterval(function() {
                BDS.gallery.nav(1);
            }, config.autoDelay * 1000);
        },
        
        // calc the limits
        calc_limits: function() {
            var taw, taa;
            taw = thumbArea.parentNode.offsetWidth;
            taa = taw / 4;
            bxs = BDS.gallery.leftpos(thumbArea);
            bxe = bxs + taa;
            fxe = bxs + taw;
            fxs = fxe - taa;
        },
    
        // get the maus pos
        pos: function(e) {
            xp = isIE ? event.clientX + document.documentElement.scrollLeft: e.pageX;
            yp = isIE ? event.clientY + document.documentElement.scrollTop: e.pageY;
            if (xp > bxs && xp < bxe && yp > ys && yp < ye) {
                BDS.gallery.scroll(-1);
            } else if (xp > fxs && xp < fxe && yp > ys && yp < ye) {
                BDS.gallery.scroll(1);
            } else {
                BDS.gallery.cancel();
            }
        },

		// scroll to the gallery at offset (1 based)
		showGallery: function( offs ) {
			this.scrollTo( offs );
			this.thumbNdx = offs;
			this.galNdx = 0;
			this.getimg( offs, false );
		},

		// scroll to the gallery at offset (1 based)
		// this does the actual work
		scrollTo: function( offs ) {
			var dlen = this.imgData.length;
			// sanity
			if( offs > dlen ) offs = dlen;
			if( offs < 0 ) offs = 0;
			// get width of one image
			var t = $('#' + config.thumbid + ' li').get();
			var iw = t[0].offsetWidth;
			// get width of thumbarea
			var w = thumbArea.parentNode.offsetWidth;
			var max = (iw * (dlen - 2)) - (w / 2);
			var dist = Math.abs((w / 2) - ((iw - 2) + (iw * offs)));
			if( dist < (w / 2)) dist = 0;
			if( dist > max ) dist = max;
			
			//alert( "  iw: " + iw + "\n   w: " + w + "\nmax:" + max + "\ndist: " + dist + "\ndlen: " + dlen + "\noffs: " + offs );
			
			if( this.galNdx < offs ) {
				//this.scroll(1);
				thumbArea.style.left = "-" + dist + 'px';
			} else {
				//this.scroll(-1);
				thumbArea.style.left = dist + 'px';				
			}
		},

        // scroll the thumbs
        scroll: function(dir) {
            clearInterval(thumbArea.timer);
            var dlen = this.imgData.length;
            var t = $('#' + config.thumbid + ' li').get();
            var l = (dir == -1) ? 0: (t[dlen - 1].offsetLeft - (thumbArea.parentNode.offsetWidth - t[dlen - 1].offsetWidth) + 20);
            thumbArea.timer = setInterval(function() { 
                BDS.gallery.mv(dir, l);
            }, config.scrollTimer);
        },
        
        // move the thumbs element
        mv: function(dir, l) {
            thumbArea.style.left = thumbArea.style.left || '0px';
            var left = thumbArea.style.left.replace('px', '');
            if (dir == 1) {
                if (l - Math.abs(left) <= config.scrollSpeed) {
                    this.cancel(thumbArea.id);
                    thumbArea.style.left = '-' + l + 'px';
                } else {
                    thumbArea.style.left = parseInt(left) - config.scrollSpeed + 'px';
                }
            } else {
                if (Math.abs(left) - l <= config.scrollSpeed) {
                    this.cancel(thumbArea.id);
                    thumbArea.style.left = l + 'px';
                } else {
                    thumbArea.style.left = parseInt(left) + config.scrollSpeed + 'px';
                }
            }
        },
    
        // cancel the auto thing
        cancel: function() {
            clearTimeout(thumbArea.timer);
        },
    
        // calc the left position
        leftpos: function(t) {
            var l = 0;
            if (t.offsetParent) {
                while (1) {
                    l += t.offsetLeft;
                    if (!t.offsetParent) {
                        break;
                    };
                    t = t.offsetParent;
                }
            } else if (t.x) {
                l += t.x;
            }
            return l;
        },
    
        // calc the top position
        toppos: function(t) {
            var p = 0;
            if (t.offsetParent) {
                while (1) {
                    p += t.offsetTop;
                    if (!t.offsetParent) {
                        break;
                    };
                    t = t.offsetParent;
                }
            } else if (t.y) {
                p += t.y;
            }
            return p;
        }
    };
} (BDS.gallery);

/*
window.onload = function() {
    BDS.gallery.load();
};
*/