/*
* jQuery Slideshow Plugin v1.3
* Author: Matt Oakes
* URL: http://www.matto1990.com/jquery/slideshow/
*
* Modifications by Meinhard Benn (http://benn.org/):
*  - fadetime setting
*
* Modifications by StyleTech Solutions (http://styletech.co.uk/):
*  - Added startPosition
*  - Added Play / Pause - 'show' and 'hide'
*  - Now allows the load of the slideshow after all other images completed
*  - Stores the last slide to be shown in a cookie - next view of page will display next slide in line 
*/

var oImageCookie = new Object();
var COOKIE_NAME = "dgImages";

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery.fn.preloadImages = function() {
var slides = this.find('img').get();
    
    jQuery.each(slides, function(i) {
    
        if (jQuery(slides[i]).attr("src") == "") {
            jQuery(slides[i]).attr("src", jQuery(slides[i]).attr("store"));
        }
    });
}

jQuery.fn.checkSlideImages = function(e, obj) {
    if (obj.complete || (obj.readyState == 'complete' && e.type == 'load')) {
        obj.setAttribute('loaded', "Y");
        var images_loaded = true;
        var slides = this.find('img').get();
        jQuery.each(slides, function(i) {
            if (jQuery(slides[i]).attr("loaded") == "N") {
                images_loaded = false;
            }
        });
        if (images_loaded) {
            if (jQuery('#' + this.attr('pauseLink')).attr('display') == 'hide') {
                jQuery('#' + this.attr('pauseLink')).css('display', 'none');
            }
            else {
                jQuery('#' + this.attr('pauseLink')).fadeIn('slow')
            }
           
            //setTimeout("jQuery('#" + this.attr('pauseButton') + "').click();", 3000);
            setTimeout("startSlideShow('" + this.attr('pauseButton') + "');", 3000);
        }
    }
}

function startSlideShow(pauseButton) {

    if (jQuery("#" + pauseButton).attr('STARTED') == 'Y') {

        // If the page is re-displayed from a link the startSlideShow is called twice (at least)
        // This causes the slide show to stop. Setting the attribute stops second click event being fired.
    }
    else {
        jQuery("#" + pauseButton).trigger('click');
        jQuery("#" + pauseButton).attr('STARTED', 'Y')
    }
}


jQuery.fn.slideshow = function(options) {
    var settings = {
        startPosition: -1,
        fadetime: 'slow',
        timeout: '6000',
        type: 'sequence',
        pauselink: null,
        showpauselink: 'hide',
        playcallback: null,
        pausecallback: null
    };

    if (options) {
        jQuery.extend(settings, options);
    }

    var slides = this.find('img').get();

    if (settings.type == 'startfrom' &&
        settings.startPosition > -1 &&
        settings.startPosition < slides.length) {

        // Check if startfrom position specified
        // Check starting position > -1
        // Check that starting position doesnt exceed number of images

        var lastViewed = settings.startPosition - 1;
        var pauseState = 0,
		current = settings.startPosition,
		last = lastViewed,
		timer = '';
    }
    else {
        var pauseState = 0,
		current = 0,
		last = 0,
		timer = '';
    }

    jQuery('#' + this.attr("pauseLink")).attr('display', settings.showpauselink.toLowerCase())

    var change = function() {
        if (pauseState == 0) {
            for (var i = 0; i < slides.length; i++) {
                jQuery(slides[i]).css('display', 'none');
            }

            jQuery(slides[last]).css('display', 'block').css('zIndex', '0');
            jQuery(slides[current]).css('zIndex', '1').fadeIn(settings.fadetime);

            if (settings.type == 'sequence') {
                if ((current + 1) < slides.length) {
                    current = current + 1;
                    last = current - 1;
                }
                else {
                    current = 0;
                    last = slides.length - 1;
                }
            }
            else if (settings.type == 'random') {
                last = current;
                while (current == last) {
                    current = Math.floor(Math.random() * (slides.length));
                }
            }
            else if (settings.type == 'startfrom') {
                if ((current + 1) < slides.length) {
                    current = current + 1;
                    last = current - 1;
                }
                else {
                    current = 0;
                    last = slides.length - 1;
                }
            }
            else {
                alert('type must either be \'sequence\' or \'random\'');
            }

            try {

                // Stores the current viewed in a cookie
                oImageCookie[window.location.href] = new Object();
                oImageCookie[window.location.href].last = current;

                var src = jQuery.toJSON(oImageCookie);

                var date = new Date();
                date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));

                jQuery.cookie(COOKIE_NAME, src, { expires: date });

                //window.status = "CHANGE: " + current;
            }
            catch (e) { }

            timer = setTimeout(change, settings.timeout);
        }
    };

    var pause = function() {
        if (pauseState == 0) {
            pauseState = 1;
            clearTimeout(timer);
            if (settings.playcallback != null) {
                settings.pausecallback(jQuery('#' + settings.pauselink));
            }
        }
        else {
            pauseState = 0;
            if (settings.type == 'startfrom') {
                timer = setTimeout(change, 3000);
            }
            else { change() };
            if (settings.playcallback != null) {
                settings.playcallback(jQuery('#' + settings.pauselink));
            }
        }
        return false;
    };

    this.css('position', 'relative');

    if (settings.pauselink != null) {
        jQuery('#' + settings.pauselink).click(pause);
    }

    if (settings.type == 'startfrom') {

        var slide_zIndex = slides.length + 1;
        var arrIndex = new Array();

        for (var i = settings.startPosition; i < slides.length; i++) {
            slide_zIndex--;
            arrIndex[i] = slide_zIndex;
        }
        if (settings.startPosition > 0) {
            for (var i = 0; i < settings.startPosition; i++) {
                slide_zIndex--;
                arrIndex[i] = settings.timeout;
            }
        }
    }

    jQuery.each(slides, function(i) {
        var img_path = jQuery(slides[i]).attr("store");
        jQuery(slides[i]).attr("loaded", "N");
        if (settings.type == 'startfrom') {
            jQuery(slides[i]).css('zIndex', arrIndex[i]).css('position', 'absolute').css('top', '0').css('left', '0');
        }
        else {
            jQuery(slides[i]).css('zIndex', slides.length - i).css('position', 'absolute').css('top', '0').css('left', '0');
        }
        jQuery(slides[i]).bind('onreadystatechange load', function(e) {
            //jQuery('#slideshow').checkSlideImages(e, this);
            jQuery('#' + this.parentNode.id).checkSlideImages(e, this);
            //            for (var i in this) {
            //                alert(i)
            //            }




            //this.checkSlideImages(e, this);
        });
        if (i == settings.startPosition) {
            jQuery(slides[i]).attr("src", jQuery(slides[i]).attr("store"));
        }
    });

    if (settings.type == 'sequence') {
        timer = setTimeout(change, settings.timeout);
        change();
    }
    else if (settings.type == 'random') {
        alert('Random')
        do {
            current = Math.floor(Math.random() * (slides.length));
        } while (current == 0);
    }
    else if (settings.type == 'startfrom') {
        change();
        pause();
    }
    else {
        alert('type must either be \'sequence\' or \'random\'');
    }

    return this;
};