﻿/// <reference path="../jQuery/jquery-1.4.1-vsdoc.js" />

//TODO:
//      Add play button and function for it
//      Overlay bug in IE, z-index might solve the problem

//global
var $this, $loadoverlay, $thumbnails, $status, $active, $next, $textoverlay;
var settings, activenr, displayNextInterval;
var slideprefix = 'slideobj_';

$.fn.lpGallery = function(options) {
    $this = $(this);

    //settings
    settings = $.extend({
        //.......................................................... LOADING
        loadbg: '#fff', //.......................................... define background color during loading process
        loadcolor: '#333', //....................................... define color text during loading process
        loadbgimg: '', //........................................... define a background image to disply during loading process
        animatefirst: false, //..................................... will fade in (animate) the first image on load when set to true
        //.......................................................... IMAGE
        width: 721, //.............................................. width of the image container
        height: 272, //............................................. height of the image container
        auto: true, //.............................................. auto swapping of images
        continous: true, //......................................... true if the shuffle should loop 
        duration: 7500, //.......................................... the period of time an image is shown
        speed: 1250, //............................................. the period of time it take to "fade out" (animate) one image and "fade in" (animate) another
        //.......................................................... THUMBNAILS
        thumbnails: false, //....................................... true if thumbnails should be displayed
        addplaybutton: false, //.................................... note: function not ready yet, comming!
        //.......................................................... TEXT OVERLAY
        overlayOpacity: 0.5, //..................................... opacity of the text overlay (accepted values are 0.0 - 1.0)
        overlayBackground: '#000', //............................... text overlay background color (can be set to "transparent")
        overlayColor: '#fff', //.................................... color of overlay text
        overlayY: 0, //............................................. text overlay y position
        overlayX: 0, //............................................. text overlay x position (0 = zero distance from bottom or top depending on "overlayBottom" setting
        overlayBottom: true, //..................................... if true then the overlay will load at the bottom of the image continer
        //.......................................................... MISC
        z: 900 //.................................................. image z-index at load (to make sure it is the top layer)
    }, options);
    
    //initializing functions
    $.loadinit();

    return this;
}

$.loadinit = function() { //initializes loading overlays, array with images and checks browser
    //modifying passed in <ul> and children <li>
    $this.addClass('lpgallery_container').css({
        'width': settings.width + 'px',
        'height': settings.height + 'px'
    });

    //creating and displaying loading overlay
    $loadoverlay = $('<li>&nbsp;</li>');
    $loadoverlay.css({
        'background': settings.loadbg + ' url(' + settings.loadbgimg + ') no-repeat 0 0',
        'width': '100%',
        'height': '100%',
        'z-index': (settings.z + 1)
    }).prependTo($this);


    //browser check
    if  ($.exeptionbrowser(7)) { //Iljas hack
        //if client is running a less compatible browser
        //skipping preload function (due to slow browser)
        $.initimg();
    }
    else {
        //creating overlay status text
        $status = $('<li>&nbsp;</li>');
        $status.css({
            'position': 'relative',
            'top': ($this.outerHeight() / 2) - 25 + 'px',
            'left': 0,
            'width': '100%',
            'text-align': 'center',
            'font-size': '50px',
            'z-index': (settings.z + 2),
            'color': settings.loadcolor
        });
        
        //creating array with image path
        var imgarray = $.makeArray($this.find('a'));
        for (var i = imgarray.length; i--; ) { imgarray[i] = $(imgarray[i]).attr("href"); }

        //preloading images and calling functions for status and complete
        $.loadimg(imgarray);
    }
}

//IMAGE PRELOAD INIT
$.loadimg = function(ia) {
    $.preimg(ia, function() {
        //$status.appendTo('body');
        $status.prependTo($this);
    }, function(l, t) {
        $status.html(Math.floor((l / t) * 100) + '%');
    }, function() {
        $.initimg($this);
    });
}

//INITIALIZE IMAGES
$.initimg = function() {
    if (!$.exeptionbrowser(7)) { //Iljas hack
        $status.remove(); //removing status text
    }
    $loadoverlay.remove(); //removing loading overlay

    $thumbnails = $('<ul></ul>');
    var slidelength = $this.find('li').length;
    var newy, relink;
    $this.find('li').each(function(e) {
        //modifying list object
        $(this).addClass(slideprefix + e);
        //modifying list object children
        if (settings.thumbnails) {
            $('<li><a href="">' + $(this).children('a:first').html() + '</a></li>').addClass(slideprefix + e).appendTo($thumbnails);
        }
        //checking to see if link has rel attribute and wether to not render a link around image
        relink = $(this).children('a:first').attr('rel');
        if (relink != '') {
            $(this).children('a:first').replaceWith('<a href="' + relink + '"><img src="' + $(this).children('a:first').attr('href') + '" alt="" /></a>');
        }
        else {
            $(this).children('a:first').replaceWith('<img src="' + $(this).children('a:first').attr('href') + '" alt="" />');
        }
        //checking to see if there is a overlay defined
        $textoverlay = $(this).children('div:first');
        if (($textoverlay.length != 0) && ($.trim($textoverlay.html()) != "")) {
            if (settings.overlayBottom) {
                newy = ($(this).children('img').height() - settings.height) + settings.overlayY + 'px';
                $textoverlay.css({ 'bottom': newy });
            }
            if (!settings.overlayBottom) {
                newy = settings.overlayY + 'px';
                $textoverlay.css({ 'top': newy });
            }
            $textoverlay.css({
                'opacity': settings.overlayOpacity,
                'background': settings.overlayBackground,
                'color': settings.overlayColor,
                'left': settings.overlayX + 'px',
                'width': '100%', //we can set this to 100% due to overflow hidden on container
                'z-index': settings.z + 2
            })
        }
        $(this).hide();
    });
    if (settings.thumbnails) {
        $thumbnails.addClass('lpgallery_thumbnails').insertAfter($this).find('a').click(function() {
            $.thumbnailClick($(this).parent('li'));
            return false;
        });
    }

    //calling function to display the first gallery image and set timer/events
    $.displayNextImage();
    //do next step if gallery has more than 1 image
    if ($this.children('li').length > 1) {
        if (settings.auto)
            displayNextInterval = setInterval("$.displayNextImage()", settings.duration);
    }
}

//DISPLAY NEXT IMAGE
$.displayNextImage = function() {
    if ($this.find('li#active').length == 0) {
        $next = $this.find('li:first');
        if (settings.animatefirst)
            $next.css('z-index', settings.z + 1).attr('id', 'active').fadeIn(settings.speed);
        else
            $next.css('z-index', settings.z + 1).attr('id', 'active').show();
    }
    else {
        $active = $this.find('li#active');
        activenr = parseInt($active.attr('class').substring($active.attr('class').indexOf('_') + 1));
        $active.removeAttr('id');
        if ((activenr + 1) == $this.find('li').length) {
            $next = $this.find('li.' + slideprefix + '0');
        }
        else {
            $next = $this.find('li.' + slideprefix + (activenr + 1));
        }
        $active.css('z-index', settings.z);
        $next.css('z-index', settings.z + 1).attr('id', 'active').fadeIn(settings.speed, function() {
            $this.find('li:not(#active)').hide();
        });
    }

    //thumbnail settings
    if (settings.thumbnails) {
        $thumbnails.find('li#tactive').removeAttr('id', 'tactive');
        $thumbnails.find('li.' + $next.attr('class')).attr('id', 'tactive');
    }
}

//THUMBNAIL CLICK
$.thumbnailClick = function(o) {
    if ($this.find('li#active').attr('class') != o.attr('class')) {
        clearInterval(displayNextInterval);
        displayNextInterval = undefined;
        $active = $this.find('li#active');
        $active.removeAttr('id');
        $next = $this.find('li.' + o.attr('class'));
        $active.css('z-index', settings.z);
        $next.css('z-index', settings.z + 1).attr('id', 'active').fadeIn(settings.speed, function() {
            $this.find('li:not(#active)').hide();
        });

        //thumbnail settings
        $thumbnails.find('li#tactive').removeAttr('id', 'tactive');
        $thumbnails.find('li.' + $next.attr('class')).attr('id', 'tactive');

        //set play button
        if (settings.addplaybutton) {
            $.setPlayButton(o, true);
        }
    }
}

//PLAY BUTTON
$.setPlayButton = function(o, reg) {
    var tmbpos = o.find('a').offset();
    var $pb = $('<a href=""></a>');
    $pb.css({
        'display': 'block',
        'width': o.find('a').outerWidth() + 'px',
        'height': o.find('a').outerHeight() + 'px',
        'position': 'absolute',
        'top': tmbpos.top,
        'left': tmbpos.left,
        'background': '#fff',
        'opacity': 0,
        'z-index': '5000'
    }).appendTo('body').fadeTo(500, 0.5).click(function() {
        displayNextInterval = setInterval("$.displayNextImage()", settings.duration);
        return false;
    });
}

//IMAGE PRELOADER
$.preimg = function(imageList, loadinit, status, callback) {
    var pic = [], i, total, loaded = 0;
    if (typeof imageList != 'undefined') {
        if ($.isArray(imageList)) {
            total = imageList.length; // used later
            if ($.isFunction(loadinit)) {
                loadinit();
            }
            for (i = 0; i < total; i++) {
                pic[i] = new Image();
                pic[i].onload = function() {
                    loaded++; // should never hit a race condition due to JS's non-threaded nature
                    if (loaded != total) {
                        if ($.isFunction(status)) {
                            status(loaded, total);
                        }
                    }
                    if (loaded == total) {
                        if ($.isFunction(callback)) {
                            callback();
                        }
                    }
                };
                pic[i].src = imageList[i];
            }
        }
        else {
            pic[0] = new Image();
            pic[0].onload = function() {
                if ($.isFunction(callback)) {
                    callback();
                }
            }
            pic[0].src = imageList;
        }
    }
    pic = undefined;
};
