/**
 * @author borislutskovsky
 * AJAX Photo Gallery for jquery - jquery.apg.js
 * 
 * @version 0.5
 * 
 * options: JSON object
 *  dir (required) : image directory (relative, based on the location of gallery.php)
 *  url_dir (optional): image directory from domain name. 
 *  ajax_dir(optional): directory where gallery.php is. by default, uses 
 *  title (optional): title of gallery
 *  displayCaption (optional): true(default)|false 
 *  width (optional): width of popup. standard CSS syntax (default is 400px);
 *  height(optional): height of popup. standard CSS syntax (default is 400px);
 *  align (optional): 
 *      vertical: center (default) | bottom | top | ..px
 *      horizontal: center(default)| left | right | ..px 
 *  border (optional) : standard CSS syntax. (default is solid 2px #cecece)
 *  imgWidth (optional): ..px, img size
 *  imgHeight(optional): ..px, img size
 *  imgLeft(optional): ..px, left offset for image inside the popup
 *  imgTop (optional): ..px, top offset for image inside the popup
 *  nav (optional):
 *      first, prev, next, last: text or html for button (default: "|<<", "<", ">", ">>|")
 *      css: JSON obj. starndard CSS syntax
 *  close (optional):
 *      content (optional): text or <img> of the close button. default "x".
 *      css: JSON obj. standard jqcss.
 *  bgOpacity (optional): css opacity. default is 0.7
 */

(function(jQuery){
    
    function _apg_resize(obj, el){
        if (el.opts !== undefined) {
            var iw = el.opts.imgWidth;
            var ih = el.opts.imgHeight;
            var il = el.opts.imgLeft;
            var it = el.opts.imgTop;
        }
        
        var pw, ph, w, h, wr, hr;
        if (iw !== undefined) {
            pw = parseInt(iw.replace('px', ''));
        } else {
            pw = el.popup.width();
        }
        
        if (ih !== undefined) {
            ph = parseInt(ih.replace('px', ''));
        } else {
            ph = el.popup.height() - el.caption.height() - el.img_container.position().top;
        }
        w = (el.popup.width() > obj.width() ? obj.width() : el.popup.width());
        h = (el.popup.height() > obj.height() ? obj.height() : el.popup.height());
        wr = w / pw;
        hr = h / ph;
        
        if (hr > wr && h > ph) {
            h = ph;
            obj.height(h);
        } else if ((wr > hr || w > pw) && w > pw) {
            w = pw;
            obj.width(w);
        }
        
        if (il === undefined) {
            il = ((pw - obj.width()) / 2).toString() + 'px';
        } else if(obj.width() != 0){
            il = (parseInt(il.replace('px', '')) + ((pw - obj.width()) / 2)).toString() + 'px';
        }
        
        if (it === undefined) {
            it = ((ph - obj.height()) / 2 + el.img_container.position().top).toString() + 'px';
        } else if (obj.height() != 0) {
            it = (parseInt(it.replace('px', '')) + ((ph - obj.height()) / 2)).toString() + 'px';
        }
        obj.css({
            position: 'absolute',
            left: il,
            top: it
        });
    }
    
    function _build_gallery(el) {
        var ajax_url = el.opts.ajax_dir;
        if (el.opts.ajax_dir === undefined) {
            ajax_url = 'gallery.php';
        } else {
            ajax_url += '/gallery.php';
        }
        var opts = {'dir': el.opts.dir};
        if (el.opts.url_dir) {
            opts.url_dir = el.opts.url_dir;
        }
        jQuery.get(ajax_url, opts, function(data, textStatus){
            if (textStatus == 'success') {
                if (el.img_container !== undefined) {
                    el.img_container.remove();
                }
                el.img_container = jQuery(data);
                el.images =  el.img_container.children('.apg_image');
                el.caption.before(el.img_container);
            }
        });        
    }
    
    function _set_caption(el) {
        var caption = jQuery(el.images[el.current_image]).attr('alt');
        if (caption !== '') {
            var c = el.caption.text(caption);
            c.css({position:'absolute'});
            var cw = c.width();
            c.css({bottom:0, left:(c.parent().width()-cw)/2});
        }
    }
    
    function _load_popup(el)
    {
        if (el.popup.css('display') == 'none') {
            _align_popup(el);
            el.current_image = 0;
            jQuery(el.images[0]).addClass('apg_current_image');
            if (el.opts.displayCaption) {_set_caption(el);}
            el.popup.css({'opacity':el.opts.bgOpacity});
            el.popup_bg.fadeIn();
            el.popup.fadeIn();
            _apg_resize(jQuery(el.images[0]).children('img'), el);
        }
    }
    
    function _close_popup(el)
    {
        if (el.popup.css('display') != 'none') {
            el.popup_bg.fadeOut();
            el.popup.fadeOut( function(){
                jQuery(el.images[el.current_image]).removeClass('apg_current_image');
            });
        }
    }
    
    function _fix_style(el) {
        el.popup.css({
            background:el.opts.background,
            height:el.opts.height,
            width:el.opts.width,
            border:el.opts.border,
            color:el.opts.color
        });
        el.nav.children('a').css({
            color:(el.opts.nav.css.color ? el.opts.nav.css.color : el.opts.color),
            backgroundColor: (el.opts.nav.css.backgroundColor ? el.opts.nav.css.backgroundColor : el.popup.css('backgroundColor'))
        });
        el.nav.children('a').hover(function(){
            jQuery(this).css({
                color:(el.opts.nav.css.backgroundColor ? el.opts.nav.css.backgroundColor : el.popup.css('backgroundColor')),
                backgroundColor:(el.opts.nav.css.color ? el.opts.nav.css.color : el.opts.color )
            });
        }, function(){
            jQuery(this).css({
                color:(el.opts.nav.css.color ? el.opts.nav.css.color : el.opts.color ),
                backgroundColor:(el.opts.nav.css.backgroundColor ? el.opts.nav.css.backgroundColor : el.popup.css('backgroundColor'))
            });
        });
        el.close.children('a').css({
            color: (el.opts.close.css.color?el.opts.close.css.color:el.opts.color),
            backgroundColor:(el.opts.close.css.backgroundColor?el.opts.close.css.backgroundColor:el.popup.css('backgroundColor'))
        });
        el.close.children('a').hover(function(){
            jQuery(this).css({
                color:(el.opts.close.css.backgroundColor?el.opts.close.css.backgroundColor:el.popup.css('backgroundColor')),
                backgroundColor:(el.opts.close.css.color?el.opts.close.css.color:el.opts.color)
            });
        }, function(){
            jQuery(this).css({
                color:(el.opts.close.css.color?el.opts.close.css.color:el.opts.color),
                backgroundColor:(el.opts.close.css.backgroundColor?el.opts.close.css.backgroundColor:el.popup.css('backgroundColor'))
            });
        });
    }
    
    function _align_popup(el) {
        var ww = document.documentElement.clientWidth;
        var wh = document.documentElement.clientHeight;
        var ph = el.popup.height();
        var pw = el.popup.width();
        var t,l;
        var pos='absolute';
        if (el.popup.css('height') == '100%' || el.popup.css('width') == '100%') {
            el.popup.css({
                position: 'absolute',
                top:'0px',
                left:'0px'
            })
            return;
        }
        el.popup_bg.css({'height':wh});
        switch(el.opts.align.horizontal) {
            case 'center':
                l=ww/2 - pw/2;
                break;
            case 'left':
                l=0;
                break;
            case 'right':
                l=ww-pw;
                break;
            default:
                l=el.opts.align.horizontal;
        }
        switch(el.opts.align.vertical) {
            case 'center':
                t=wh/2 - ph/2;
                break;
            case 'bottom':
                t=wh-ph;
                break;
            case 'top':
                t=0;
                break;
            default:
                t=el.opts.align.vertical;
        }
        
        el.popup.css({
            'position':pos,
            top:t+'px',
            left:l+'px'
        });
    }
    
    function _apg_next(el){
        if(el.current_image < (el.images.length - 1)) {
            jQuery(el.images[el.current_image]).removeClass('apg_current_image');
            el.current_image++;
            jQuery(el.images[el.current_image]).addClass('apg_current_image');
            _apg_resize(jQuery(el.images[el.current_image]).children('img'), el);
            if (el.opts.displayCaption) {_set_caption(el);}
        }
    }
    
    function _apg_prev(el){
        if(el.current_image != 0) {
            jQuery(el.images[el.current_image]).removeClass('apg_current_image');
            el.current_image--;
            jQuery(el.images[el.current_image]).addClass('apg_current_image');
            _apg_resize(jQuery(el.images[el.current_image]).children('img'), el);
            if (el.opts.displayCaption) {_set_caption(el);}
        }
    }
    
    function _apg_first(el) {
        jQuery(el.images[el.current_image]).removeClass('apg_current_image');
        el.current_image = 0;
        jQuery(el.images[el.current_image]).addClass('apg_current_image');
        _apg_resize(jQuery(el.images[el.current_image]).children('img'), el);
        if (el.opts.displayCaption) {_set_caption(el);}
    }
    
    function _apg_last(el) {
        jQuery(el.images[el.current_image]).removeClass('apg_current_image');
        el.current_image = el.images.length - 1;
        jQuery(el.images[el.current_image]).addClass('apg_current_image');
        _apg_resize(jQuery(el.images[el.current_image]).children('img'), el);
        if (el.opts.displayCaption) {_set_caption(el);}
    }
    
    jQuery.fn.apg = function(options){
        apgDefaults = {
            background: '#000000',
            color:'#ffffff',
            width: '400px',
            height: '400px',
            border:'2px solid #cecece',
            padding:'12px',
            fontSize:'0.8em',
            title:'',
            align: {
                horizontal:'center',
                vertical:'center'
            },
            nav: {
                first: '|&lt;&lt;',
                prev : '&lt;',
                next : '&gt;',
                last : '&gt;&gt;|',
                css: {}
            },
            close: {
                content: 'x',
                css: {}
            },
            bgOpacity: '0.7'
        };
    
        return this.each(function(i){
            var el = {};
            el.jqthis = jQuery(this);
            el.opts   = jQuery.extend({}, apgDefaults, options);
            el.opts.nav = jQuery.extend(apgDefaults.nav, options.nav);
            el.opts.close = jQuery.extend(apgDefaults.close, options.close);
            el.index  = i;
            el.popup  = jQuery('<div id="apg_' + el.id + '" class="apg_popup">');
            el.popup_bg = jQuery('<div id="popup_bg">');
            el.apg_title  = jQuery('<div id="title">' + el.opts.title + '</div>');
            el.close  = jQuery('<div id="close"><a>' + el.opts.close.content + '</a></div>');
            el.popup.prepend(el.apg_title);
            el.popup.prepend(el.close);
            el.popup.append(jQuery('<br/>'));
            el.nav    = jQuery('<div class="apg_nav" align="center"></div>');
            el.nav.css(el.opts.nav.css);
            el.first  = jQuery('<a href="javascript:void(0);">' + el.opts.nav.first + '</a><span>&nbsp;&nbsp;</span>');
            el.prev   = jQuery('<a href="javascript:void(0);">' + el.opts.nav.prev + '</a><span>&nbsp;&nbsp;</span>');
            el.next   = jQuery('<a href="javascript:void(0);">' + el.opts.nav.next + '</a><span>&nbsp;&nbsp;</span>');
            el.last   = jQuery('<a href="javascript:void(0);">' + el.opts.nav.last + '</a>');
            el.nav.append(el.first);
            el.nav.append(el.prev);
            el.nav.append(el.next);
            el.nav.append(el.last);
            el.popup.append(el.nav);
            el.popup.append(jQuery('<br/>'));
            el.caption = jQuery('<div id="caption">');
            el.popup.append(el.caption);
            _fix_style(el);
            jQuery('body').append(el.popup);
            jQuery('body').append(el.popup_bg);
            el.close.click(function(){_close_popup(el);});
            el.popup_bg.click(function(){_close_popup(el);});
            el.next.click(function(){_apg_next(el);});
            el.prev.click(function(){_apg_prev(el);});
            el.last.click(function(){_apg_last(el);});
            el.first.click(function(){_apg_first(el);});
            _build_gallery(el);
            el.jqthis.click(function(){_load_popup(el);});
        });
    }
})(jQuery);

