﻿/// <reference path="../jQuery/jquery-1.4.1-vsdoc.js" />

//TODO:
//      Add play button and function for it
//      Hide text on init
//      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({
        //image related
        width: 800,
        height: 500,
        auto: true,
        continous: true,
        duration: 3000,
        speed: 1000,
        loadbg: '#252525',
        loadcolor: '#eaeaea',
        loadbgimg: 'Javascript/Plugin/Image/loading_text.png',
        thumbnails: true,
        animatefirst: true,
        z: 1000,
        //text overlay related
        overlayOpacity: 0.5,
        overlayBackground: '#000',
        overlayColor: '#fff',
        overlayY: 0,
        overlayX: 0,
        overlayBottom: true
    }, 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()) {
        //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()) {
        $status.remove(); //removing status text
    }
    $loadoverlay.remove(); //removing loading overlay

    $thumbnails = $('<ul></ul>');
    var slidelength = $this.find('li').length;
    var newy;
    $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);
        }
        $(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
        $.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;
};


//HELPERS
$.exeptionbrowser = function() {
    var str = 'MSIE';
    if (navigator.appVersion.match(str)) {
        var version = navigator.appVersion;
        version = version.substr(version.indexOf(str) + (str.length + 1), 1);
        version = parseInt(version);
        if (version <= 7)
            return true;
        else
            return false;
    }
    else
        return false;
}

function cl(str) {
    console.log(str);
}
