/*
* Very Simple Image Gallery navigation add-ons (keyboard and arrow link support)
* Copyright 2010 Paul Pullen 
* http://www.pepwebsolutions.com
* paul@pepwebsolutions.com
*/

jQuery(document).ready(function () {
    //get total number of gallery pics
    var picsCount = jQuery('div.vsig_thumb').size();

    //add numbers to each pic
    jQuery('div.vsig_thumb a').each(function (i) {
        jQuery(this).addClass("" + (i + 1) + "");
    });

    //insert an instructions div
    jQuery('div.vsig_top').after('<div class="instructions">Click on each picture or use the left and right arrow keys to navigate.<a class="vsig_back" href="#"> << </a><span class="photoCount"><\/span><a class="vsig_forward" href="#"> >> </a></div>');
    //insert the photoCount div content
    jQuery('span.photoCount').html(function () {
        return ' Viewing Photo <span class="picNum">1<\/span> of ' + picsCount + '.';
    });
	
	//for nav button clicks:
	jQuery('a.vsig_back').click(function(e){
                e.preventDefault();
		var direction = null;
		direction = 'prev';
		changePicture(direction);
                return false;
	});
	
	jQuery('a.vsig_forward').click(function(e){
                e.preventDefault();
		var direction = null;
		direction = 'next';
		changePicture(direction);
                return false;
	});
	
    //watch for keyboard events
    jQuery(document).keyup(function (event) {
        //initialize the direction variable
        var direction = null;

        if (event.keyCode == 37) {
            //select left image
            direction = 'prev';

        } else if (event.keyCode == 39) {
            //select right img
            direction = 'next';
        }
	changePicture(direction);

    });

    //for mouse clicks:
    jQuery("div.vsig_thumb a").click(function () {
        //get this link's id
        var picNumber = jQuery(this).attr("class");
        //and write it into the div
        jQuery('span.picNum').html(function () {
            return picNumber;
        });

    });
	
	//function to change pics
	function changePicture(leftOrRight) {
		
		var direction = leftOrRight;
	
	        //find the currently displayed large image's title to compare to thumbnails
        var largeImgTitle = jQuery('div.vsig_top img').attr("title");

        //find the thumb with matching title attribute and go up/down from here to click the selected picture
        jQuery("div.vsig_thumb a[title='" + largeImgTitle + "']").parent().parent()[direction]().find('a').click();

        //get the new large image title
        var largeImgTitle = jQuery('div.vsig_top img').attr("title");

        //get this thumb's pic number and write it into the picNum span
        picNumber = jQuery("div.vsig_thumb a[title='" + largeImgTitle + "']").attr("class");
        jQuery('span.picNum').html(function () {
            return picNumber;
        });
	
	}

});
