if (typeof(require) == "function") {
    var gui         = require('nw.gui');
    var win         = gui.Window.get();
}
var $slides         = $('div.slide');
var $stepHandler    = $('#step-handler');
var $activeSlide;

function getActiveSlide() {
    $activeSlide = $('div.slide.active');

    if ($activeSlide.length === 0) {
        $activeSlide = $('div.slide[data-id="1"]');
        $activeSlide.addClass('active');
    }
}

function onStepClickHandler() {
    var id = $(this).data('id');

    $activeSlide.removeClass('active');
    $('div.slide[data-id="' + id + '"]').addClass('active');

    getActiveSlide();

    $stepHandler.find('li.selected').removeClass('selected');
    $stepHandler.find('li[data-id="' + id + '"]').addClass('selected');
}

function generateStepHandler() {
    var selectedSlideId = $activeSlide.data('id');
    var id;
    var isSelected;

    $.each($slides, function (i, slide) {
        id         = $(slide).data('id');
        isSelected = selectedSlideId === id;

        $stepHandler.append('<li class="step '+ (isSelected ? 'selected' : '') + '" data-id="' + id + '"></li>');
    });

    $stepHandler.on('click', 'li.step', onStepClickHandler);
}

function stepLeft() {
    var id      = $activeSlide.data('id') - 1;
    var $prev   = $('li.step[data-id="' + id + '"]');

    if ($prev.length > 0) {
        $prev.click();
    }
}

function stepRight() {
    var id      = $activeSlide.data('id') + 1;
    var $next   = $('li.step[data-id="' + id + '"]');

    if ($next.length > 0) {
        $next.click();
    }
}

$(document).keydown(function(e) {
    switch(e.which) {
        case 37: stepLeft(); break;
        case 39: stepRight(); break;

        default: return;
    }
    e.preventDefault();
});

function init() {
    getActiveSlide();
    generateStepHandler();
}

init();
