﻿/**
* Fade in and out block elements 
* @author    Jacob Stellingwerf
*/
(function($){
 /*
  Chain functions down here
  */

 /*
  Function description here
  */
  $.fn.slideShow = function(options) {
    var cfg = $.extend({
      hideSpeed: 2000,
      showSpeed: 2500,
      interval: 3000,
      startAfter: 1500,
      center: false
    }, options||{})
  
    var slideshow = $(this);
    var interval = null;
    
    if (cfg.center) {
      slideshow.find("> *").each(function() {
        $.setCenterPoint(slideshow, this);
      });
    }
    
    slideshow.find("> *:first").show();
    slideshow.find("> *:gt(0)").hide().css($.extend(cfg.cssHideAnimate||{}, cfg.cssHide||{}, { opacity: 0}));
    
    var counter = 1;
    var max = slideshow.find("> *").size();

    var slide = function() {
      var current = slideshow.find("> *::nth-child("+counter+")");
      counter++;
      if (counter > max) {
        counter = 1;
      } 
      var next = slideshow.find("> *::nth-child("+counter+")");    
      
      current.animate({opacity: 0}, cfg.hideSpeed, function() { $(this).hide() });
      next.show().animate({opacity: 1}, cfg.showSpeed, function() { $(this).css("opacity", "") });
    };
    
    window.setTimeout(function() { 
      slide();
      interval = window.setInterval(slide, cfg.interval);  
      $(window).unload(function() { clearInterval(interval); });
    }, cfg.startAfter)

    $(this).click(function() {
      clearInterval(interval);
    });

    return $(this);
  };

 /*
  Global functions down here
  */
  
 /*
  Sets and returns a upperleft corner coordinate based on given arguments to center child.
  */  
  $.setCenterPoint = function(view, obj) {
    var retObj = { 
      viewport: { 
        width: $(view).width(),
        height: $(view).height()
      },
      obj: { 
        width: $(obj).width(),
        height: $(obj).height()
      }
    }
    
    var centerPoint = {
      left: Math.round((retObj.viewport.width - retObj.obj.width) / 2),
      top: Math.round((retObj.viewport.height - retObj.obj.height) / 2)
    }
    
    $(obj).css($.extend({ position: "absolute" }, centerPoint));
    
    return centerPoint;
  };  
})(jQuery);
