﻿(function($) {

    // These work by breaking the file path into an array based upon the
    // '/' character, taking the file name, and either adding or removing
    // a final folder named hover.


    $.fn.rollOver = function(options) {
        // Our options
    var opts = $.extend({}, $.fn.rollOver.defaults, options)

        // The defaults for our options
        $.fn.rollOver.defaults = {
            markCurrentPage: false,
            currentPage: '',
            directory: 'hover'
        }
        
        // This removes the last directory in a path
        // argument taken is an $('img')
        removeLastDirectory = function(i) {
            var newPath = i.attr('src').split('/')
            var fileName = newPath[newPath.length - 1]
            newPath.pop()
            newPath[newPath.length - 1] = fileName
            return newPath.join('/')
        }
        
        // This adds a hover folder as the last folder in a path
        // argument taken is an $('img')
        addHoverDirectory = function(i) {
            var newPath = i.attr('src').split('/')
            var fileName = newPath[newPath.length - 1]
            newPath[newPath.length - 1] = opts.directory
            newPath.push(fileName)
            return newPath.join('/')
        }

        // The first function is the hover event, the second the mouse out
        this.hover(
            function() {
                $(this).attr('src', addHoverDirectory($(this)))
            },
            function() {
                $(this).attr('src', removeLastDirectory($(this)))
            });

        // Preload the images
        this.each(function() {
            $(this).clone().attr('src', addHoverDirectory($(this))).remove()
        });

        // Now we mark the current page and clear the hover events if the options tell us to
        if (opts.markCurrentPage) {
            var currentPageImg = $(this).parent().parent().find('a[href=' + opts.currentPage + '] img')

            currentPageImg.attr('src', addHoverDirectory(currentPageImg))
            currentPageImg.unbind()
        }

        // Continue the chain
        return $(this)
    }

3})(jQuery);