(function($){
    $.jImageRotate = function(el, options){
      
      $.jImageRotate.defaultOptions = {
        dynamic : 40,
        speed : 14,
        startSpeed : 14,
        perspective : 0.3,
        decelerateTime : 10,
        decelerateIntensity : 2,
        maxSpeed : 20,
        background : 'images/background.jpg'
      };
  
      var base = this;
            
      base.$el = $(el);
      base.el = el;
      
      base.$el.data("jImageRotate", base);
      var iWidth;
      var iHeight;
      var ySpin = 0;
      var xSpin = 0;
      var ctx;
      var posY = 20;
      var img;
      var img2;
      var mouseAbsX = 0;
      var mouseAbsY = 0;
      var defaultSpeed;
      var actImage;
      var rotation = 0;
      var rotationSize = 0;
      var rNew = 0;
      var direction;
      var isMouseOver = false;
      var intervalDecel;
      var decelerateIntensity = 0; 
      var actSpeed;     
      var startTimer = 0;
      var stopTimer = 0;
      var d = new Date();
      var fps = 0;
      var img2 = new Object();
      
      var t;
      var t1;
      
      base.init = function(){
        base.interval;
        base.options = $.extend({},$.jImageRotate.defaultOptions, options);
        base.$el.css('display','none');
        // Rotationsrichtung bestimmen
        defaultSpeed = base.options.speed;
        actSpeed = base.options.startSpeed;
        if (base.el.nodeName == 'IMG') {
          img = new Image();
          base.loadImage(img);
        }
        if (base.el.nodeName == 'VIDEO') {
          img = new Object();
          img = base.el;
          base.loadVideo(img);
        }          
        // Hintergrundbild  
        img.src = base.el.src;
        img2 = new Image();
        img2.onload = function() {
        }
        img2.src = base.options.background;
        actImage = img;
      }
      
      // Bild laden
      base.loadImage = function(img) {
        window.clearTimeout(t1);
        if (base.el.width == 0) {
          t1 = window.setTimeout(function() {base.loadImage(img)}, 10);
        }
        else {    
          $(base.el).parent().append('<canvas id="canvas_'+base.el.id+'" width="'+base.el.width+'" height="'+(base.el.height * 2)+'" class="canvas">');
          // Events
          $('#canvas_'+base.el.id).bind({mousemove: function(event) {base.mouseMove(event)}});
          $('#canvas_'+base.el.id).bind({mouseenter: function(event) {base.mouseEnter(event)}});
          $('#canvas_'+base.el.id).bind({mouseleave: function(event) {base.mouseLeave(event)}});
          ctx = document.getElementById('canvas_'+base.el.id).getContext('2d'); 
          iWidth = base.el.width;
          rotationSize = iWidth * 2;
          iWidth = iWidth / 2;
          iHeight = base.el.height;
          base.startRotation();
        }
      }
      
      
      // Video laden
      base.loadVideo = function(img) {
        window.clearTimeout(t);
        if (!img.currentSrc)
          t = window.setTimeout(function() {base.loadVideo(img)}, 150);
        else {
        img = new Object();
          $(base.el).parent().append('<canvas id="canvas_'+base.el.id+'" width="'+base.el.width+'" height="'+(base.el.height * 2)+'" class="canvas">');
          // Events
          $('#canvas_'+base.el.id).bind({mousemove: function(event) {base.mouseMove(event)}});
          $('#canvas_'+base.el.id).bind({mouseenter: function(event) {base.mouseEnter(event)}});
          $('#canvas_'+base.el.id).bind({mouseleave: function(event) {base.mouseLeave(event)}});
          ctx = document.getElementById('canvas_'+base.el.id).getContext('2d'); 
          iWidth = base.el.videoWidth;
          rotationSize = iWidth * 2;
          iWidth = iWidth / 2;
          iHeight = base.el.videoHeight;
          base.startRotation();
        }
      }

   
        
      base.imageRotate = function() {
        if (actSpeed > 0)
          rotation = rotation - Math.abs(actSpeed)/10;
        else
          rotation = rotation + Math.abs(actSpeed)/10;  
        
        if (rotation > rotationSize)
          rotation = 0;
        if (rotation < 0)
          rotation = rotationSize;
   
        rNew = rotation/rotationSize;
        rNew = Math.cos(2*Math.PI*rNew);
        if (rotation < 0.5*rotationSize)
          rNew = (rNew + 1)* -1 -1;
        rNew = (rNew + 3) / 4 * rotationSize;
   
        if (rNew < rotationSize / 2)  
          xSpin = rNew;
        if (rNew >= rotationSize / 2)  
          xSpin = (rotationSize - rNew);
          
        if (rotation < rotationSize / 4)  
          ySpin = rotation * base.options.perspective;  
        if ((rotation >= rotationSize / 4) && (rotation < rotationSize / 2)) 
          ySpin = (rotationSize/2 - rotation) * base.options.perspective;
        if ((rotation >= rotationSize / 2)  && (rotation < rotationSize * 3/4)) 
          ySpin = (rotationSize/2 - rotation) * base.options.perspective;
        if (rotation >= rotationSize * 3/4)
          ySpin = -(rotationSize - rotation) * base.options.perspective;
        ctx.clearRect(0,0,base.el.width,base.el.height * 2);
        for (i=0;i<(iWidth*2);i++) {
          ctx.drawImage(actImage, i, 0, 1, iHeight, i+Math.round(xSpin/(iWidth/(iWidth-i))), posY+(ySpin*(iWidth-i))/iWidth, 1,  posY+iHeight-((ySpin*(iWidth-i))/iWidth)*2 );  
            
        }
  
        if ((rotation < rotationSize / 4) || (rotation >= rotationSize * 3/4))
          actImage = img;
        else {
          actImage = img2;
          //base.stopRotation();
          //alert(actImage);
        }
      }
 
      
      // Rotation starten
      base.startRotation = function() {
        base.interval = window.setInterval(function() {base.imageRotate()}, base.options.dynamic);
      }
      
      // Rotation stoppen
      base.stopRotation = function() {
        window.clearInterval(base.interval);
      }
      
      // Mausposition ermitteln
      base.getMouseRelX = function() {
        return mouseAbsX - iWidth;
      }
      
      // Abbremsen
      base.decelerate = function() {
        decelerateIntensity = decelerateIntensity + base.options.decelerateIntensity
        if (actSpeed > 0)
          actSpeed = actSpeed - 1;
        else
          actSpeed = actSpeed + 1;
        window.clearTimeout(intervalDecel);
        if (Math.abs(actSpeed) > defaultSpeed)
          intervalDecel = window.setTimeout(function() {base.decelerate()}, base.options.decelerateTime + base.options.decelerateTime * decelerateIntensity/10);
        else {
          if (actSpeed > 0)
            actSpeed = base.options.speed;
          else
            actSpeed = - base.options.speed;
          window.clearTimeout(intervalDecel);
          decelerateIntensity = base.options.decelerateIntensity;
        }
        
      }
      
      // Events
      base.mouseMove = function(e) {
        mouseAbsX = e.pageX-$('#canvas_'+base.el.id).offset().left;
        mouseAbsY = e.pageY-$('#canvas_'+base.el.id).offset().top;
        if (isMouseOver) {
          actSpeed = base.getMouseRelX()*base.options.maxSpeed/10;
        }
      }
      
      base.mouseEnter = function(e) {
        isMouseOver = true;
        window.clearTimeout(intervalDecel);
      }
      
      base.mouseLeave = function(e) {
        isMouseOver = false;
        //intervalDecel = window.setInterval(function() {base.decelerate()}, 300);
        base.decelerate();
      }
      
      /*************************************************************/
      /* extern functions                                           */
      /*************************************************************/
      
            
      /*************************************************************/
      /* Run initializer                                           */
      /*************************************************************/
      base.init();
  };
 
  
  $.fn.jImageRotate = function(options){
    return this.each(function(){
        (new $.jImageRotate(this, options));
    });
  };
  
})(jQuery);

function GetRandom( min, max ) {
	if( min > max ) {
		return( -1 );
	}
	if( min == max ) {
		return( min );
	}
  return( min + parseInt( Math.random() * ( max-min+1 ) ) );
}
