﻿var CampgroundSlider = (function () {
    var index = 0;
    var secondindex = 0;

    var $options = null;

    var $firstimg = null;
    var $secondimg = null;
    var $preloader = null;
    var $elem = null;
    var $prev = null;
    var $next = null;

    var Previous = function () {
        index--;
        LoadCarousel();
        ShowPreloader();
    };

    var Next = function () {
        index++;
        LoadCarousel();
        ShowPreloader();
    };

    var LoadCarousel = function () {
        secondindex = 0;

        if (index == $options.data.length)
            index = 0;

        if (index == -1)
            index = $options.data.length - 1;

        ((index + 1) != $options.data.length) ? secondindex = index + 1 : secondindex = 0;

        $firstimg.attr({ "src": $options.data[index].url + ".axd?preset=leftlargesquare", title: $options.data[index].title, alt: $options.data[index].title });
        $secondimg.attr({ "src": $options.data[secondindex].url + ".axd?preset=rightlargesquare", title: $options.data[secondindex].title, alt: $options.data[secondindex].title });

        //hide preloader
        $firstimg.load(function () {
            $('#campgroundsliderPreloader').hide();
        });
        //hide if error as well
        $firstimg.error(function () {
            HidePreloader();
        });
    };

    var ShowPreloader = function () {
        $('#campgroundsliderPreloader').show();
    };

    var HidePreloader = function () {
        $('#campgroundsliderPreloader').hide();
    };

    return {
        init: function (options, elem) {
            // Mix in the passed in options with the default options
            this.options = $.extend({}, this.options, options);

            //save private variable options
            $options = this.options;

            // Save the element reference, both as a jQuery
            // reference and a normal reference
            this.elem = elem;
            $elem = $(elem);

            $firstimg = $('li.first img.Imagefirst', $elem);
            $secondimg = $('li.second img.Imagesecond', $elem);

            $preloader = $('#campgroundsliderPreloader');

            $prev = $('.carousel-prev', this.elem);
            $next = $('.carousel-next', this.elem);

            //load events
            $prev.click(Previous);
            $next.click(Next);

            //call load carousel on page load
            LoadCarousel();

            // return this so we can chain/use the bridge with less code.
            return this;
        },
        options: {
            data: null
        }
    }
})();
