/*This function was designed for Maine Accessibility Corporation's website's use with permission.
It is released under GPL: http://www.gnu.org/licenses/gpl.html
Copyright 2011 Kurt Osgood
Author:   Kurt Osgood
Website:  www.truk.tk
Email:	 truk@truk.tk
Version:  0.5
Date:     5-15-2011
Requires: jQuery v1.3.2 or later
			 cycle-lite v1.1 or later

The fadeabunch function simply polls through a subfolder for images with the same name and address of the defined image,
and up to 50 numbers after. The image MUST have a number before the extension. If javascript is disabled, 
it will just show the first image. Fadeabunch must be called from within the div. Make sure cycle lite (regular should 
work as well,) jquery, and this file are included. All images will end up with the same alt-text as the first. Positioning 
should be done in the div. I'm not checking file types other than being 1-4 chars, that is YOUR job. Use ones commonly 
supported by img tags. 

A basic call for a div with id="someid":
$('#someid').fadeabunch();


This was made fairly simple, but can be made to do some real work from here. All optionals have default values below.

numafter if the number of filenames after the start the code will check. (not including the original)(optional)
IE: If you set numafter to 5, and you have files:
	www.mysite.com/may5pics-32.jpg
	www.mysite.com/may5pics-35.jpg
	www.mysite.com/may5pics-36.jpg
	www.mysite.com/may5pics-38.jpg
	
The code will fade through numbers 32, 35, and 36, but 38 will not be shown.
The lower the number, the faster the page loads, so use the lowest working number.

holdpic is the delay between pictures in ms. (optional)

transtime is the time in ms it takes to transition from one image to another. (optional)

Full call with options for a div with id="someid":
$('#someid').fadeabunch({
		numafter:  8,
		holdpic:   2500,
		transtime: 1500
	});

*/


;(function( $ ){
	
  $.fn.fadeabunch = function(tehopts) {
    
    /*Set defaults*/
    tehopts = $.extend({numafter: 20, holdpic: 4000, transtime: 2500}, tehopts);    
    	
	 return this.each(function() {  
    	/*Setup*/
    	var defclass  = "goodimg";      /*Default class name for images that are good, used only if image has no class already*/
    	var c;
    	var addedc = 0;
    	var itssrc = '';
    	var divused = this;

      /*loads of error checking*/
      var imgused = divused.getElementsByTagName('img')[0];
    	var extnsn  = imgused.src.substr(imgused.src.lastIndexOf('.') + 1); /*result is the image's extension (usually .jpg)*/

      if ((imgused.className == '') || (imgused.className == 'null')) {
        var imgclass = defclass;
        imgused.className = imgclass;
    	}
    	else {
        var imgclass = imgused.className;
    	}
    	if (extnsn.length > 4) {
    	  window.console && console.log("Extension over 4 characters, assuming invalid: "+extnsn);
        return this;
    	}
    	if (extnsn.length < 1) {
    	  window.console && console.log("Extension not found: "+extnsn);
        return this;
    	}
    	if ((imgused.src.replace('.' + extnsn, '').match(/\d+$/)) == 'null') {
    	  window.console && console.log("No ending number, can't figure out what image is next!");
        return this;
    	}

    	/*Setting up, with defaults when needed*/
    
    	var strtnum = imgused.src.replace('.' + extnsn, '').match(/\d+$/);   /*result is the last set of numbers before the extension*/
    	strtnum = strtnum * 1;                                               /*Turn string into number*/
    	var path = imgused.src.replace(strtnum + '.' + extnsn, '');          /*result is the path without the numbers or the extension*/
    	if (imgused.alt == "null") {
        var tehalt = '';
    	}
    	else {
        var tehalt = imgused.alt;
    	}

    	/*Go through all the pics and set them up to load
    	Loaded images are set to the same class to cycle through. 
    	Missing images are removed, but they still waste time in loading*/
    	for (c = 1; (c <= tehopts.numafter); c++) {
        addedc = strtnum + c;
        itssrc = path + addedc + '.' + extnsn;
        document.write('<img style="display: none;" src="' + itssrc + '" alt="' + tehalt + '" onload="onaload(this,\'' + imgclass + '\')" onerror="removeanobj(this)" />');
    	}

    	/*Wait until page has loaded all images before un-hiding and displaying them*/
    	window.onload = function() {
        var dispclass = '.' + imgclass;
        var expr4img = 'img.' + imgclass;
    	  var wdth = getmax('goodimg',"width");    /*Width in pixels of the largest picture*/
    	  var hght = getmax('goodimg',"height");   /*Height in pixels of the largest picture*/

        $(dispclass).css('display', 'inline'); /*Make sure all the good images are going to show*/

        $(divused).cycle({
            fx:       'fade',
            speed:     tehopts.transtime,
            timeout:   tehopts.holdpic,
            next:      divused,
            pause:     1,
            width:     wdth,
            height:    hght,
            slideExpr: expr4img
        });
    	};
    
    });
};

/*Returns max width or height, call only after all have loaded (window.onload.)*/
function getmax(cn,dmnsn) {
	if((dmnsn != 'width') && (dmnsn != 'height')) {
		window.console && console.log("Must be width or height: "+dmnsn);
      return this;
	}
	
	var objs = $('.'+cn);

	var tehmax = 0;	
	
	objs.each(function() {  
		var elmsize = (dmnsn == "width")? this.width : this.height;
		tehmax = (elmsize > tehmax)? elmsize : tehmax;
	});
	return tehmax; 
}

})(jQuery);

/*changes the class once loaded so that cycle can see them*/

function onaload(toclass, tehclass) {
    toclass.className = tehclass;
}

/*Removes object pointed to, in case of non-existant pics*/

function removeanobj(donewith) {
    $(donewith).remove();
}

