
//$(document).ready(function() { 	
(function($) {

    $.fn.innerblink = function(options) {	
        return this.each(function() {   
            $.innerblink(this, options);
            
            
        });
    };
    $.fn.restartblink = function(options) {	
        return this.each(function() {   
        
            //ok, reset the globals
            for(i=0; i<$.banner.handles.length ;i++){
              clearTimeout( $.banner.handles[i] );
            };
            for(i=0; i<$.banner.displayed.length ;i++){           
              if (typeof($.banner.displayed[i])=="undefined") {              
                  $.banner.displayed[i]=$.banner.buffer[i];
                  delete $.banner.buffer[i];
							}	
            };
            $.innerblink(this, options);
        });
    };

    $.innerblink = function(container, options) {
        var settings = {        	
            'speed':            7000,
            'imgWidth':         150,
            'overlap':  		    30,
            'overflow':         'outside',
            'align':            'center',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        var elements = new Array();
        if (settings.children === null)
            //elements = elements.concat($(container).children());
            elements = $(container).children();
        else
            elements = elements.concat($(container).children(settings.children));
			
        //Randomize
        randomize(elements,true);
        //elements.randomize(true);
        
        //Make them all disappear
        for (var i = 0; i < elements.length; i++) {
                    $(elements[i]).css('position', 'absolute').hide();
                };
        
        //Distribute them across the document
        var docwidth = $(container).width();
        if (docwidth==0)
            docwidth = $(container).parent().width();
        var spacing = settings.imgWidth-settings.overlap;
        var numelements = 0;
        var pad = 0;
        if (settings.overflow == 'outside') {
          numelements = Math.floor((docwidth/spacing)+1);        
          numelements = Math.min(numelements, elements.length);	
        } else {
          numelements = Math.floor((docwidth/spacing));   
          numelements = Math.min(numelements, elements.length);	
        }

        //figure out how much space is left over, split it and start there
        pad=(docwidth-(settings.imgWidth*numelements))/2;      
        //make sure our parent is wide enough
        $(container).width(docwidth+(Math.abs(pad)*2));
        //now figure out where to put it

        if (settings.align == 'right') {
            //$(container).css('margin-left',$(window).width()-$(container).parent().offset().left-$(container).width());
            $(container).css('margin-left',$(window).width()-$(container).width());
        } else if (settings.align == 'left') {
            $(container).css('margin-left',0);
        } else { //center
            $(container).css('left',$(container).parent().offset().left);
            $(container).css('margin-left',pad);
        }
        
         
        //Create our "globals" for screen buffers
        $.banner = {};
        $.banner.displayed = new Array(numelements);
        $.banner.buffer = new Array(numelements);
        $.banner.hidden = new Array(elements.length-numelements);
        $.banner.handles = [];
        
        //Populate the buffers (essentially randomly)
        var i=0;
        for (i = 0; i < numelements; i++) {
          //$(elements[i]).css('left',pad+(spacing*i)).show();
          $(elements[i]).css('left',(spacing*i)).show();
          $.banner.displayed[i]=$(elements[i]);
        };
        var j=0
        for (;i<elements.length;i++){
          $.banner.hidden[j]=$(elements[i]);
          j++;
        }
        
        //Setup 3 images to change at prime intervals.
        //The loop in $.blink will restart after 10 seconds, so we get images changing at
        //3, 5, 7, 13, 15, 17, 23 ... seconds	
        $.banner.handles.push(setTimeout(function() {		
          $.blink(settings.speed, pad, spacing);
        }, 3000));		
        $.banner.handles.push(setTimeout(function() {		
          $.blink(settings.speed, pad, spacing);
        }, 5000));	
        $.banner.handles.push(setTimeout(function() {		
          $.blink(settings.speed, pad, spacing);
        }, 7000));		
	}
	$.blink = function(speed, pad, spacing) {
		//randomly pick an displayed image
		var display = Math.floor ( Math.random () * ( $.banner.displayed.length ) );		
		
		//if the one we picked is already being used, skip this round
		if (typeof($.banner.displayed[display])!="undefined") {
			var fromdisplayed = $($.banner.displayed[display]);		
			//remove the image and mark the space "undefined"
			delete $.banner.displayed[display];

			//randomly pick a hidden image
			var hide = Math.floor ( Math.random () * ( $.banner.hidden.length ) );
			//var hide=0;			
			var fromhidden = $($.banner.hidden[hide]);
			if(typeof(fromhidden) == "undefined" || $(fromhidden).attr('src')=="undefined") {
				//alert("uh oh on " + hide);
			}
			//we put it in the buffer so we know its appropriate index in displayed
			$.banner.buffer[display]=fromhidden;
			//remove it from the hidden buffer (no need for undefined here)
			$.banner.hidden.splice(hide,1);

			
			//find the x position of the displayed image
			var left = $(fromdisplayed).css('left');
			var beforefilter = $(fromdisplayed).css('filter');
			//hide the displayed one
			$(fromdisplayed).fadeOut(speed,
						function() {						
							//put the filter back as its lost in IE
							$(this).css('filter',beforefilter);
							//removeFilter($(this)[0]);
							//add it to the hidden so it can come back later
							$.banner.hidden.push($(this));
							//console.log("hiding: " + $(this).attr("src"));
							
						});
			//set the x position of the image to appear and show it
			//$(fromhidden).css('left',pad+(spacing*display)).fadeIn(speed,			
      $(fromhidden).css('left',(spacing*display)).fadeIn(speed,			
						function() {
							//put the filter back as its lost in IE
							$(this).css('filter',beforefilter);
							
							//removeFilter($(this)[0]);
							var buffer = $.banner.buffer
							//console.log(buffer.length);
							
							//indexOf didn't seem to work, so we just look for the src attribute
							var index =-1;
							for(i=0; i<buffer.length ;i++){
								if ($(buffer[i]).attr("src")==$(this).attr("src")){
									index = i;
									break;
								}
							}							 
							
							//console.log("showing: " + $(this).attr("src") + " at " + index);
							//put the image at the approprate index in displayed
							$.banner.displayed[index]=$(this);
							//remove it from the buffer
							delete $.banner.buffer[index];
						});
					

		} else {
			//well, looks like we've hit a race collision.  Guess we'll just move along and do nothing
		}
		//Call this function again, or, eventually things'll just stop
		$.banner.handles.push(setTimeout(function() {
			$.blink(speed, pad, spacing);
		}, 10000));
	}
	// **************************************************************************
	// Copyright 2007 - 2009 Tavs Dokkedahl
	// Contact: http://www.jslab.dk/contact.php
	//
	// This file is part of the JSLab Standard Library (JSL) Program.
	//
	// JSL is free software; you can redistribute it and/or modify
	// it under the terms of the GNU General Public License as published by
	// the Free Software Foundation; either version 3 of the License, or
	// any later version.
	//
	// JSL is distributed in the hope that it will be useful,
	// but WITHOUT ANY WARRANTY; without even the implied warranty of
	// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	// GNU General Public License for more details.
	//
	// You should have received a copy of the GNU General Public License
	// along with this program. If not, see <http://www.gnu.org/licenses/>.
	// ***************************************************************************

	// Randomize elements in an array
	//Array.prototype.randomize=
	//function(ru) {
	function randomize(element, ru) {
		if (!ru)
		  element.sort(function(){return ((Math.random() * 3) | 0) - 1;});
		else {
		  //var a = [].concat(element);
		  var a=[];
		  for (var i = 0; i < element.length; i++) {
                a[i]=element[i];
            };
		  var l = element.length;
		  var al = n = 0;
		  for(var i=0; i<l; i++) {
			al = a.length;
			// Get random integer in [0,a.length-1]
			n = Math.floor((Math.random() * al));
			// Copy random element from a to this
			element[i] = a[n];
			// If n was last element in a just pop a[n]
			if (n == al - 1)
			  a.pop();
			// Else copy last element from a to n and pop last element from a
			else {
			  a[n] = a[al - 1];
			  a.pop();
			}
		  }
		}
    };
    
	function num(el, prop) {
    return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
  };
})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}

