/**
 * ID Gallery - Image slideshow by Pavel Politov (politov@gmail.com)
 *
 * Copyright (c) 2007 Infodesigner.ru (http://www.infodesigner.ru/)
 * Freely distributable under MIT-style license.
 *
 */
jQuery.fn.idgallery = function(settings) {
    settings = jQuery.extend({
        easeFunc: 'easeInOutExpo',
        easeTime: 750,
        flashTime: 250,
        interval: 3000,
        divphoto: 'divphoto',
        lang: 'rus'
    }, settings);
    modes = {
        preview:1,      //onclick preview icon
        prev:2, next:3  //navigate with controls, autoplay
    };
    var show;
    return this.each(function(){
        var df = 'df';
        // Build DOM
        jQuery('ul.preview').before('<div class="frame"/>');
        var preview = jQuery('ul.preview').wrap('<div class="previewFrame"/>');
        var w = 0; preview.children('li').each(function(){w+=jQuery(this).width();});
        preview.width(w);
        var frame = jQuery('div.frame');
        var slider = jQuery('<ul class="slider"/>').appendTo(frame);
        var cnt = 0;
        preview.children('li')
            .each(function() { //slider images
                var a = jQuery(this).find('a');
                var target = 'slider'+ cnt++;
                a.attr('target',target);
                var alt = a.children('img').attr('alt') || '';
                var prefix = (settings.divphoto=='albumphoto') ? 'album' : 'photo';
                var wbase = (settings.divphoto=='albumphoto') ? 14 : 12;
                var twidth = (settings.divphoto=='albumphoto') ? 530 : 526;
                var str = ['<li id="'+target+'"><div class="'+settings.divphoto+'">',
                    '<table width="',twidth,'" cellspacing="0" cellpadding="0" border="0">',
                    '<tr><td width="',wbase,'" valign="top"><img src="/images/',prefix,'-lt.png" alt=""/></td><td valign="top"><img src="/images/',prefix,'-t.png" width="100%" height="',wbase,'" alt=""/></td><td width="',(wbase+2),'" valign="top"><img src="/images/',prefix,'-rt.png" alt=""/></td></tr>',
                    '<tr><td style="background:url(/images/',prefix,'-l.png) left repeat-y"></td>',
                    '<td align="center" valign="middle" class="divphoto-img">',
                    '<img src="'+a.attr('href')+'" alt="'+alt+'" />',
                    '</td>',
                    '<td style="background:url(/images/',prefix,'-r.png) left repeat-y"></td></tr>',
                    '<tr><td><img src="/images/',prefix,'-lb2.png" alt=""/></td><td><img src="/images/',prefix,'-b2.png" width="100%" height="',(wbase+3),'" alt=""/></td><td><img src="/images/',prefix,'-rb2.png" alt=""/></td></tr>',
                    '</table>', '</div></li>'];
                var li = jQuery(str.join('')).appendTo(slider);
                jQuery(this).children('h3').clone().appendTo(li).end().remove();
            })
            .find('a').click(function(){ // click on preview
                stopSlide();
                preview.children('li').removeClass('visible');
                slider.children('li').removeClass('visible');
                jQuery(this).parent().parent().addClass('visible');
                slider.find('#'+jQuery(this).attr('target')).addClass('visible');
                slide(slider, modes.preview);
                return false;
            });
        slider.children('li').each(function(){
            jQuery(this).find('h3.photoplace').before('<div class="separator-dotted"><img src="/images/cp.gif" alt="" border="0"/></div>');
        });
        var descshow = (settings.lang=='eng') ? 'read description' : 'читать подпись';
        var deschide = (settings.lang=='eng') ? 'close description' : 'закрыть подпись';
        function toggle_detail(f) {
            if (f) {
                var div = slider.find('li.visible');
                var h = div.find('h3.photoplace').height();
                h += div.find('h3.photodesc').height();
                if (!div.attr('defheight')) { div.attr('defheight', div.height()); }
                div.addClass('detailed')
                    .height(parseInt(div.attr('defheight'))+h+10)
                    .find('h3').show();
                div.parent().parent().height(div.height());
                jQuery('div.photodetail').text(deschide);
            } else {
                jQuery('li.detailed').removeClass('detailed').each(function(){
                    var defheight = parseInt(jQuery(this).attr('defheight'));
                    jQuery(this).find('h3.photoplace').hide().end()
                        .find('h3.photodesc').hide().end()
                        .height(defheight)
                        .parent().parent().height(defheight);
                });
                jQuery('div.photodetail').text(descshow);
            }
        }
        jQuery('<div class="photodetail">'+descshow+'</div>').appendTo(frame)
            .click(function(){ toggle_detail(!slider.find('.visible').hasClass('detailed')); });
        preview.children('li').eq(0).addClass('visible');
        slider.children('li').eq(0).addClass('visible');

        // Previews highlight
        //preview.children('li').each(function(){
        //    jQuery('<div class="flash"/>').appendTo(this)
        //        .css({opacity:'.01'}).width(jQuery(this).width())
        //        .mouseover(function(){
        //            jQuery(this).css({opacity:'.80'}).stop().animate({opacity:'.01'}, settings.flashTime);
        //        }).click(function(){
        //            jQuery(this).prev().children('a').trigger('click');
        //        });
        //});

        // Loading fx
        var imagesloaded = 0;
        var loaddiv = jQuery('div.loading');
        if (loaddiv.length == 0) {
            loaddiv = jQuery('<div class="loading">подготовка альбома ...</div>').appendTo(frame);
        }
        var totalimg = slider.find('.divphoto-img>img').size();
        slider.find('.divphoto-img>img').load(function(){
            imagesloaded++;
                var wdth = 0;
                slider.children('li').each(function(){wdth+=jQuery(this).width();});
                slider.width(wdth);
            if (imagesloaded == totalimg) {
                loaddiv.hide();
            } else if (imagesloaded > totalimg*0.75) {
                loaddiv.css('background-position','12px -57px');
            } else if (imagesloaded > totalimg*0.50) {
                loaddiv.css('background-position','12px -37px'); startSlide();
            } else if (imagesloaded > totalimg*0.25) {
                loaddiv.css('background-position','12px -17px');
            }
        });

        // Controls
        var controls = jQuery('div.controls');
        controls.find('img').hover(function(){
            this.src = this.src.replace(/\.gif/, '_.gif');
        }, function() {
            this.src = this.src.replace(/_\.gif/, '.gif');
        });

        controls.children('.play').click(startSlide);
        controls.children('.pause').click(stopSlide);
        controls.children('.prev').click(function(){stopSlide(); slide(slider,modes.prev); slide(preview,modes.prev); });
        controls.children('.next').click(function(){stopSlide(); slide(slider,modes.next); slide(preview,modes.next); });

        function slide(ul, mode) {
            mode = mode || modes.next;
            //if (ul.queue('fx').length > 0) {return;} // prevent multiple clicks
            //if (jQuery('li.detailed').size() > 0) { toggle_detail(false); }
            if (mode == modes.next) {
                if (ul.children('.visible').next().length > 0) {
                    ul.children('.visible').removeClass('visible').next().addClass('visible');
                } else {
                    ul.children('.visible').removeClass('visible');
                    ul.children('li').eq(0).addClass('visible');
                }
            } else if (mode == modes.prev) {
                if (ul.children('.visible').prev().length > 0) {
                    ul.children('.visible').removeClass('visible').prev().addClass('visible');
                } else {
                    ul.children('.visible').removeClass('visible');
                    ul.children('li').slice(-1).addClass('visible');
                }
            }
            var offset = 0;
            var visible = ul.children('.visible');
            var total = 0; ul.children('li').each(function(){total+=jQuery(this).width()});
            var totalleft = 0; visible.prevAll().each(function(){totalleft+=jQuery(this).width()});
            var delta = total/ul.children('li').size();
            var framewdth = ul.parent().width();
            var curleft = parseInt(ul.css('left'));
            if (totalleft >= framewdth) {
                offset = -totalleft;
                if ((total - totalleft) < framewdth) {
                    offset = framewdth - total;
                }
            }
            var easing = (settings.easeFunc in jQuery.easing) ? settings.easeFunc : '';
            if (ul.hasClass('preview')) {
                ul.parent().stop().animate({scrollLeft: -offset}, settings.easeTime, easing);
                //setTimeout('jQuery("ul.preview .visible .flash").mouseover()', settings.easeTime*0.75);
            } else {
                ul.stop().animate({left: offset}, easing);
            }
            if (jQuery('li.detailed').length > 0) {toggle_detail(true);}
        }

        function startSlide() {
            clearInterval(show);
            show = setInterval(function(){slide(slider); slide(preview);}, settings.interval);
            controls.children('.play').hide().end().children('.pause').show();
        }

        function stopSlide() {
            clearInterval(show);
            controls.children('.pause').hide().end().children('.play').show();
        }
    });
};