﻿/// <reference path="jQuery.intellisense.js" />
$(function() {
    var i = 0;
    var files = [], imgloc;

    imgloc = $('#thumbs').attr('title');
    $.ajax({
        url: imgloc + 'index.txt',
        timeout: 5000,
        success: CreateThumbs,
        error: function(xhr) {
            $('#debug').html('error: ' + xhr.status + ' ' + xhr.statusText);
        }
    });

    function SetSrc(n) {
        if (i == files.length) { return; }
        $('#thumb' + i).removeClass("selected");
        i = n;
        $('#mainimg').fadeOut('fast', function() {
            SelectImg();
            $(this).fadeIn('slow');
        });
    }

    function SelectImg() {
        $('#thumb' + i).addClass("selected");
        $('#mainimg').css('background-image', "url('" + (imgloc + files[i]) + "')");
        if (i == 0) { $('#prev').hide(); }
        else { $('#prev').show(); }
        if (i == files.length - 1) { $('#next').hide(); }
        else { $('#next').show(); }
    }

    function CreateThumbs(data) {
        files = $.grep(data.split(/\n/), function(line) { return line; });
        //files = data.split(/\r\n/);

        $.each(files, function(a, fname) {
            var id = 'thumb' + a;
            $('#thumbs').append('<img src="' + imgloc + 'thumbs/' + fname.replace(/\r/,"") + '" id="' + id + '" />');
            $('#' + id).click(function() {
                SetSrc(a);
            });
        });
        SelectImg();
        $('#next').click(function() { SetSrc(i + 1); });
        $('#mainimg').click(function() { SetSrc(i + 1); });
        $('#prev').click(function() { SetSrc(i - 1); });
    }
});
