jQuery.fn.rotate = function(angle,whence) {
    var p = this.get(0);

    // we store the angle inside the image tag for persistence
    if (!whence) {
        p.angle = ((p.angle==undefined?0:p.angle) + angle) % 360;
    } else {
        p.angle = angle;
    }

    if (p.angle >= 0) {
        var rotation = Math.PI * p.angle / 180;
    } else {
        var rotation = Math.PI * (360+p.angle) / 180;
    }
    var costheta = Math.cos(rotation);
    var sintheta = Math.sin(rotation);

    if (document.all && !window.opera) {
        var canvas = document.createElement('img');

        canvas.src = p.src;
        // Modified when height and width are sourced so that it works in IE7, which used to just return 0 for both.
        //canvas.height = p.height;
        //canvas.width = p.width;

        canvas.onload = function() {
            canvas.height = p.height;
            canvas.width = p.width;
        }
        
        canvas.style.filter = "progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')";
    } else {
        var canvas = document.createElement('canvas');
        if (!p.oImage) {
            canvas.oImage = new Image();
            // Added following as suggested in http://code.google.com/p/jquery-rotate/issues/detail?id=3
            canvas.oImage.onload = function() {
                canvas.style.height = p.height;
                canvas.style.width = p.width;

                canvas.style.width = canvas.width = Math.abs(costheta*p.width) + Math.abs(sintheta*p.height);
                canvas.style.height = canvas.height = Math.abs(costheta*p.height) + Math.abs(sintheta*p.width);


                var context = canvas.getContext('2d');
                context.save();
                if (rotation <= Math.PI/2) {
                    context.translate(sintheta*p.height,0);
                } else if (rotation <= Math.PI) {
                    context.translate(canvas.width,-costheta*p.height);
                } else if (rotation <= 1.5*Math.PI) {
                    context.translate(-costheta*p.width,canvas.height);
                } else {
                    context.translate(0,-sintheta*p.width);
                }
                context.rotate(rotation);
                context.drawImage(canvas.oImage, 0, 0, p.width, p.height);
                context.restore();
            }
            canvas.oImage.src = p.src;
        } else {
            canvas.oImage = p.oImage;
        }

    }
    canvas.id = p.id;
    canvas.angle = p.angle;
    p.parentNode.replaceChild(canvas, p);
}

jQuery.fn.rotateRight = function(angle) {
    this.rotate(angle==undefined?90:angle);
}

jQuery.fn.rotateLeft = function(angle) {
    this.rotate(angle==undefined?-90:-angle);
}

