﻿/*
	called like this:
	var rounded = window.RoundedImages;
	rounded.round(img,radius); // this is fastest
	rounded(img)(img)(img);
*/
;(function($, window, document, undefined) {

    window.RoundedImages = (function() {
        var isIE = $.browser.msie == true,
			ns = 'v', // vml namespace
			supportStyle = $.support.style == true, // does the browser support copying of styles other than cssText
			supportCanvas = (function() {
			    return typeof document.createElement('canvas').getContext == 'function';
			})();
        if (!supportCanvas) { // add stylesheets to make VML work in IE
            if (document.namespaces[ns] == null) {
                var e = ["shape", "shapetype", "group", "background", "path", "formulas", "handles", "fill", "stroke", "shadow", "textbox", "textpath", "imagedata", "line", "polyline", "curve", "roundrect", "oval", "rect", "arc", "image"],
					s = document.createStyleSheet(),
					j = e.length;
                while (j--) {
                    s.addRule(ns+"\\:" + e[j], "behavior: url(#default#VML); display:inline-block;");
                }
                s.addRule(ns+"\\:var", "zoom:1;");
                document.namespaces.add(ns, "urn:schemas-microsoft-com:vml");
            }
        }
        var setStyle = function(newImg, oldImg) { // used to copy align styles from old image to new rounded
            var align = oldImg.getAttribute('align'),
				$newImg = $(newImg),
				styleObj = {};
            if (align) {
                switch (align.toLowerCase()) {
                    case 'left':
                    case 'right':
                        styleObj['float'] = align;
                        break;
                    case 'bottom':
                    case 'top':
                    case 'middle':
                    case 'absmiddle':
                    case 'absbottom':
                        styleObj['verticalAlign'] = align;
                        break;
                }
            }
            newImg.className = oldImg.className;
            $newImg.parent('a').addClass('rounded');
            $newImg.css(styleObj);
        };
        var doRound = function(img, radius) {
            var img = img,
				radius = (radius || 20),
				imgStyle,
				tmpImg,
				oldStyle;
            imgStyle = img && img.style ? img.style : {};
            if (!img || img.rounded == true) { // its hidden, or has already been rounded
                return;
            }
            img.setAttribute('class', (img.className ? img.className + ' hasbeenrounded' : 'hasbeenrounded'));
            img.setAttribute('rounded', true);
            // save the current style, so we can apply it later
            if (supportStyle) {
                oldStyle = img.getAttribute('style');
            } else {
                oldStyle = img.style.cssText;
            }
            if (!supportCanvas) { // We know IE to not support Canvas element. Yet. When IE9 comes around, this will have to be changed
                
                var doRoundInIe = function() {
                    var tmpImg = this,
						part,
						vml,
						inner,
						vmlStyle,
						gStyle,
						rStyle,
						width,
						height;
					if (img.attributes['width'] && img.attributes['width'].specified != 0) {
						width = img.getAttribute('width');
					}
					if (img.attributes['height'] && img.attributes['height'].specified != 0) {
						height = img.getAttribute('height');
					}
                    if (!width) {
                        width = this.width;
                    }
                    if (!height) {
                        height = this.height;
                    }
                    imgStyle.display = 'none';

                    part = Math.min(width, height) / 100;
                    radius = Math.max(Math.min(100, radius / part), 0) + '%'; // create radius percentage out of size of the image

                    vml = document.createElement('<var>');
                    vmlStyle = vml.style;
                    if (supportStyle) {
                        vml.setAttribute('style', oldStyle);
                    } else {
                        vmlStyle.cssText = oldStyle;
                    }
                    // overwrite default styles with these, to ensure the look and dimensions
                    vmlStyle.overflow = 'hidden';
                    vmlStyle.display = 'inline-block';
                    vmlStyle.width = width + 'px';
                    vmlStyle.height = height + 'px';
                    vmlStyle.padding = '0px';
                    vmlStyle.margin = vmlStyle.margin || '0'; // just one off, nobody knows why...

					gStyle = 'zoom:1; margin:0; padding:0; position:relative; width:' + width + 'px;height:' + height + 'px;';
					rStyle = 'position:absolute; margin:-1px 0 0 -1px;padding:0; width:' + width + 'px;height:' + height + 'px;display:block;';
					
                    // this is the easiest way of doing it, instead of creating elements
                    inner = '<'+ns+':group style="'+gStyle+'" coordsize="' + width + ',' + height + '">'
						  +		'<'+ns+':roundrect arcsize="' + radius + '" strokeweight="0" filled="t" stroked="f" fillcolor="#ffffff" style="'+rStyle+'">'
						  +			'<'+ns+':fill src="' + this.src + '" type="frame" />'
						  +		'</'+ns+':roundrect>'
						  + '</'+ns+':group>';

                    vml.innerHTML = inner;
                    img.parentNode.insertBefore(vml, img);
                    setStyle(vml, img);
                };
                if (!img.complete) { // not completed, create tmp image to add onload handler to
                    tmpImg = new Image();
                    tmpImg.onload = doRoundInIe;
                    tmpImg.src = img.src;
                } else {
                    doRoundInIe.call(img);
                }
            } else { // do the Canvas greatness
                var canvas = document.createElement('canvas'),
					x = 0, y = 0,
					parent = img.parentNode

                var doRoundWithCanvas = function() {
					if (!this.complete) {
						return; // not gonna happen at this point :(
					}
                    var width = img.hasAttribute('width') === true ? img.getAttribute('width') : this.width,
					    height = img.hasAttribute('height') === true ? img.getAttribute('height') : this.height;

					// useless check, it only happens in chrome and safari when the images are cached...
					if (width < 1) {
						width = this.width;
					}
					if (height < 1) {
						height = this.height;
					}
					    
                    width = parseInt(width,10);
                    height = parseInt(height,10);

                    canvas.width = width;
                    canvas.height = height;

                    parent.insertBefore(canvas, img);

                    if (supportStyle) {
                        canvas.setAttribute('style', oldStyle);
                    } else {
                        canvas.style.cssText = oldStyle;
                    }

                    var ctx = canvas.getContext("2d");

                    ctx.beginPath();
                    ctx.moveTo(x, y + radius);
                    ctx.lineTo(x, y + height - radius);
                    ctx.quadraticCurveTo(x, y + height, x + radius, y + height); // bottom left
                    ctx.lineTo(x + width - radius, y + height);
                    ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius); // bottom right
                    ctx.lineTo(x + width, y + radius);
                    ctx.quadraticCurveTo(x + width, y, x + width - radius, y); // top right
                    ctx.lineTo(x + radius, y);
                    ctx.quadraticCurveTo(x, y, x, y + radius); // top left
                    ctx.closePath();

                    ctx.clip();
                    ctx.fillStyle = 'rgba(255, 255, 255, 0)'; // 0 is the alpha channel, otherwise it will have a white outline

                    ctx.fillRect(x, y, width, height);
                    try {
						ctx.drawImage(this, x, y, width, height);
                    } catch(e) {
						// error accured when apsx error page instead of image > not real image data
                    }

                    setStyle(canvas, img);
                };
                imgStyle.display = 'none';

                if (!img.complete) {
                    tmpImg = new Image();
                    tmpImg.onload = doRoundWithCanvas;
                    tmpImg.src = img.src;
                } else {
                    debug = false;
                    doRoundWithCanvas.call(img);
                }
            }
        };
        var api = function() {
            return api.round.apply(null, arguments);
        }
        api.round = function(arg1,arg2) {
            doRound(arg1,arg2);
        }
        return api;
    })();
    /*
    This is purely for LEGO Universe. We get the images and map their classes to the correct radius.
    */
    $().ready(function() {
		/*
		if ( $.browser.msie == true) {
			var consoleEle = $('<div style="background:#000;color:#fff;position:fixed;top:0;left:0;padding:10px;z-index:99999;" id="console" />').appendTo('body').get(0);
			window.console = {
				log : function() {
					var a = arguments,
						l = arguments.length,
						html = "<br />";
					for (var i = 0; i < l; i++) {
						html += a[i] + "&nbsp;";
					}
					consoleEle.innerHTML += html;
				}
			}
		}
		*/
        var images = $('img.rounded, img.rounded-tiny, img.rounded-slideshow').get(), // find all images
			i = images.length,
			imageRadius = { // object with references to the classnames with radiues
			    'rounded': 8,
			    'rounded-tiny': 8,
			    'rounded-slideshow': 30
			},
			rFunc;
        if (i > 0) {
            rFunc = window.RoundedImages;
            while (i--) { // this is by far the fastes loop;
                var img = images[i], // rewrite out of jquery?
						clsName = img.className ? img.className.split(' ')[0] : 'rounded';
                if (img) {
                    rFunc.round(img, imageRadius[clsName]);
                }
            }
        }
    });
})(jQuery, window, document);

