﻿/// <reference path="jQuery/jquery-1.3.2-vsdoc.js" />

var g_slide = (function () {

    try {
    if (noSlideShow != null)
        if (noSlideShow)
            return;
    } catch (e) {

    }


    // Constants
    var c_targetName = "splodge";
    var c_target = "#" + c_targetName;
    var c_count = 12;

    // Properties
    var _current = {
        index: null,
        nextIndex: function () {
            if (this.index == null || ++this.index > c_count)
                this.setIndex(1);
            else this.setIndex(this.index);

            return this.index;
        },
        setIndex: function (index) {
            if ((index + 1) > c_count)
                index = 1;

            this.index = index;
        }
    };

    var _interval = null;

    var _path = "/content/images/splodges/splodge{i}.jpg";

    // Methods
    var _init = function () {
        if (_current.index == null)
            _current.setIndex(Math.ceil(Math.random() * c_count));

        if ($(c_target).length == 0)
            $("body").prepend("<div id=\"" + c_targetName + "\"></div>");
    };

    var _changeBackground = function (idx) {
        var url = _path.replace(/{i}/, idx);
        var img = new Image();
        img.onload = function () {
            $(c_target).fadeOut(function () {
                $(c_target).css({ backgroundImage: "url(" + url + ")" });
                $(c_target).fadeIn();
            });
        };
        img.src = url;
    };

    var _start = function () {
        _stop();
        _init();
        _interval = setInterval(function () {
            _changeBackground(_current.nextIndex());
        }, 20000);

        _changeBackground(_current.index);
    };

    var _stop = function () {
        if (_interval)
            clearInterval(_interval);
    };

    // Events
    $(document).ready(function () {
        if (g_speed && g_speed.isSlow())
            return;

        if (!$("body").hasClass("home"))
            _start();
    });

    return {
        start: _start,
        stop: _stop
    };
})();