﻿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);

    var orientation = 1;
    if (p.angle != 0)
        orientation = -1;

    if (document.all && !window.opera) {
        var canvas = document.createElement('img');

        canvas.src = p.src;
        canvas.height = p.height;
        canvas.width = p.width;
        canvas.style.filter = "progid:DXImageTransform.Microsoft.Matrix(M11=" + orientation + ",M12=" + 0 + ",M21=" + 0 + ",M22=" + 1 + ",SizingMethod='auto expand')";
    } else {
        var canvas = document.createElement('canvas');
        if (!p.oImage) {
            canvas.oImage = new Image();
            canvas.oImage.src = p.src;
        } else {
            canvas.oImage = p.oImage;
        }

        canvas.style.width = canvas.width = Math.abs(costheta * canvas.oImage.width) + Math.abs(sintheta * canvas.oImage.height);
        canvas.style.height = canvas.height = Math.abs(costheta * canvas.oImage.height) + Math.abs(sintheta * canvas.oImage.width);

        var context = canvas.getContext('2d');
        context.save();
        context.setTransform(orientation, 0, 0, 1, canvas.oImage.width, 0);


        //context.rotate(rotation);
        context.drawImage(canvas.oImage, 0, 0, canvas.oImage.width, canvas.oImage.height);
        context.restore();
    }
    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);
}

