// pet-it.js
// Sample JavaScript solution for Lab 6: Pet-It
// INFO 343, Autumn 2012
var CURRENT_BREED = 0; // currently selected breed
var BREEDS = []; // array of all breed names as strings
// Make ajaxError handle all Ajax errors.
$.ajaxSetup({ error: ajaxError });
// When the page is ready, attach event handlers.
$(document).ready(function() {
$("#dogs, #cats").change(getBreeds);
$("#next").click(nextClick);
});
// Get the list of breeds indicated by the currently-selected radio button.
function getBreeds() {
$.get(this.id + ".txt", injectBreeds);
}
// Populate the Breeds list with the given list of breeds.
function injectBreeds(data) {
// Clear previous list.
$('#breeds ul').html('');
// Create a new <li> for each breed in the list, and inject it into the ul in
// the #breeds sidebar.
BREEDS = data.split("\n");
for (var i = 0; i < BREEDS.length; i++) {
$("<li>").text(BREEDS[i]).appendTo("#breeds ul");
}
// Display the first of the breeds.
showBreedDescription(0);
}
// Displays the image and description for the breed at the given index in the
// 'breeds' list (and image for the next breed).
function showBreedDescription(index) {
// Determine the name of this breed's image/html file.
var currentfilename = BREEDS[index].toLowerCase().replace(" ", "_");
// Fetch & inject description of this breed.
$('#description').load("breeds/" + currentfilename + ".html");
// Display this breed's image.
$("#pet").attr('src', "breeds/" + currentfilename + ".jpg");
// Set up the next breed's image.
var nextindex = (index + 1) % BREEDS.length;
var nextfilename = BREEDS[nextindex].toLowerCase().replace(" ", "_");
$("#next img").attr('src', "breeds/" + nextfilename + ".jpg");
// Highlight the name of the currently-displayed breed in the list.
$('.selected').removeClass('selected');
$('#breeds ul li').eq(index).addClass("selected");
}
// Advance to next breed in the list (wrapping around to the first if at the end).
function nextClick() {
CURRENT_BREED = (CURRENT_BREED + 1) % BREEDS.length;
showBreedDescription(CURRENT_BREED);
}
// Provided Ajax failure code.
function ajaxError(xhr, type, error) {
alert("Error making Ajax request!\n\n" +
"Status code: " + xhr.status + "\n" +
"Status text: " + error + "\n\n" +
"Full text of response:\n" + xhr.responseText);
}