var selected;
var interval;
var features;

$(document).ready(function(){
    $.get("features.xml",function(xml){
        features = $('feature_item', xml);
        selected = Math.floor(Math.random() * features.size());

        populate(features);
        switch_feature(features.eq(selected));

        $("#pausebutton").click(function() {
            $("#pausebutton").hide();
            $("#autobutton").show();
            pause();
        });

        $("#autobutton").click(function() {
            $("#autobutton").hide();
            $("#pausebutton").show();
	    interval = setInterval("next(features)", 10000);
        });

        $("#nextbutton").click(function() {
            if(selected >= (features.size() - 1))
                next = 0;
            else
                next = selected + 1;
            switch_feature(features.eq(next));
        });

        $("#prevbutton").click(function() {
            if(selected <= 0)
                prev = (features.size() - 1);
            else
                prev = selected - 1;
            switch_feature(features.eq(prev));
        });

        features.each(function() {
            $("#flink" + $(this).attr("id")).click(function() {
                $("#pausebutton").hide();
                $("#autobutton").show();
                pause();
                switch_feature(features.eq($(this).attr("id").charAt(5) - 1));
            });
        });
    });

    play();
});

function populate(items) {
    feature_list = '<div id="spryregion1">';
    items.each(function(i) {
        id = $(this).attr("id");
        feature_list += '<div><div id="flink' + id + '" class="f-link">';
        feature_list += $(this).find("title").text() + '</div></div>';
    });
    feature_list += '</div>';

    $("#features_DIV").append(feature_list);
}

function switch_feature(item) {
    var img = new Image();
    $(img).load(function() {
        selected_title = '<a href="' + item.find("location").text() + '">' + item.find("title").text() + '</a>';
        selected_image = '<div><img src="' + item.find("largeimage").text() + '" alt="" /></div>';
        

        $(".hp-feature-description").html(item.find("description").text());
        $(".slider1-feature-head").html(selected_title);

        $("#Features_image_DIV").html(this);
        $(this).fadeIn("slow");
    }).attr('src', item.find("largeimage").text());
        $("#flink" + (selected + 1)).css("background-color", "rgb(0,42,86)");
        $("#flink" + item.attr("id")).css("background-color", "rgb(0,25,52)");
    selected = item.attr("id") - 1;
}

function next(features) {
    if(selected >= (features.size() - 1))
        switch_feature(features.eq(0));
    else
        switch_feature(features.eq(selected + 1));
}

function play() {
    interval = setInterval("next(features)", 10000);
}

function pause() {
    try {
        clearInterval(interval);
    } catch(e) { }
}
