/**
* jquery.imgCorners.js
*
* v1.2
*
* Create images whith rounded corners using canvas element.
* 
* License: GPL
* 
* Usage: 
*  $(selector).imgCorners([options])
*
* Supported options:
*   radius - (int) radius size of corners
*       
*   Examples:
*   $('#example_1').imgCorners();
*   $('#example_4').imgCorners({ radius: 20 });
*/

(function($) {

	
	if($.browser.msie) { // init IE
		if(document.namespaces['v']==null) {
			var ss = document.createStyleSheet();
			ss.addRule("v\\:roundrect","behavior: url(#default#VML);");
			ss.addRule("v\\:fill","behavior: url(#default#VML);");
			document.namespaces.add("v","urn:schemas-microsoft-com:vml");
		}
	} 
	
	function isBorderRadiusSupported(elem) {
		var s = elem.style;
		return typeof s.borderRadius === "string" ||
		   typeof s.WebkitBorderRadius === "string" ||
		   typeof s.KhtmlBorderRadius === "string" ||
		   typeof s.OperaBorderRadius === "string" ||
		   typeof s.MozBorderRadius === "string";
	};

	function addCornersCSS(img, radius) {
		var r = radius + 'px';
		$(img).css({
			'border-radius' : r,
			'-webkit-border-radius' : r,
			'-khtml-border-radius' : r,
			'-opera-border-radius' : r,
			'-moz-border-radius' : r
		});
	}
	
	function addCornersIE(img, radius) {

		var vml, data, w, h, cstyle, arcsize, display = "", flt = "";
		
		w = img.width;
		h = img.height;
		arcsize = (w > h) ? radius/h : radius/w;

		display = (img.currentStyle.display.toLowerCase()=='block')?'block':'inline-block';
		vml = document.createElement('<var style="zoom:1; display:' + display + '; width:' + w + 'px; height:' + h + 'px; padding:0;">');
		flt =  img.currentStyle.styleFloat.toLowerCase();
		display = (flt=='left'||flt=='right')?'inline':display;
		data = '<v:roundrect stroked="f" arcsize="' + arcsize + '" filled="t" fillcolor="#333333" style="zoom:1;margin:-1px 0 0 -1px;padding:0;display:' + display + ';width:' + w + 'px;height:' + h + 'px;"><v:fill src="' + img.src + '" type="frame" /></v:roundrect>';
		vml.innerHTML = data;
		
		vml.className = 'imgCorners';
		vml.style.cssText = img.style.cssText;
		
		cstyle = img.currentStyle;
		// TODO - надо доделать и другие свойства, либо класс присваивать таким элементам
		vml.style.marginTop = cstyle.marginTop;
		vml.style.marginRight = cstyle.marginRight;
		vml.style.marginBottom = cstyle.marginBottom;
		vml.style.marginLeft = cstyle.marginLeft;

		//vml.style.visibility = 'visible';
		vml.src = img.src; 
		vml.alt = img.alt;
		
		if(img.id){ 
			vml.id = img.id;
		}
		if(img.title) {
			vml.title = img.title;
		}
	
		img.insertAdjacentElement('BeforeBegin', vml);
		img.style.display = 'none';

	}

	function addCorners(img, radius) {
		
		var canvas, ctx, w, h, cstyle;

		canvas = document.createElement('canvas');
		w = img.width;
		h = img.height;

		if(canvas.getContext) {
			
			canvas.className = 'imgCorners';

			canvas.style.cssText = img.style.cssText;

			cstyle = getComputedStyle(img, null);
			// TODO - надо доделать и другие свойства, либо класс присваивать таким элементам
			canvas.style.marginTop = cstyle.marginTop;
			canvas.style.marginRight = cstyle.marginRight;
			canvas.style.marginBottom = cstyle.marginBottom;
			canvas.style.marginLeft = cstyle.marginLeft;
			
			canvas.height = h;
			canvas.width = w;
			canvas.style.height = img.height + 'px';
			canvas.style.width = img.width + 'px';
			canvas.src = img.src;
			canvas.alt = img.alt;
			
			if(img.id) { 
				canvas.id = img.id;
			}
			if(img.title) {
				canvas.title = img.title;
			}

			ctx = canvas.getContext("2d");

			img.parentNode.replaceChild(canvas, img);

			ctx.clearRect(0, 0, w, h);

			ctx.beginPath(); 
			ctx.moveTo(0, radius);
			ctx.lineTo(0, h - radius); 
			ctx.quadraticCurveTo(0, h, radius, h);
			ctx.lineTo(w - radius, h); 
			ctx.quadraticCurveTo(w, h, w, h - radius);
			ctx.lineTo(w, radius);
			ctx.quadraticCurveTo(w, 0, w - radius, 0);
			ctx.lineTo(radius, 0);
			ctx.quadraticCurveTo(0, 0, 0, radius);
			//ctx.closePath();
			
			//ctx.clip();
			ctx.fillStyle = '#333333';
			ctx.fill();
			
			ctx.globalCompositeOperation = "source-atop";
			ctx.drawImage(img, 0, 0, w, h);

			//canvas.style.visibility = 'visible';
			
			//ctx.fillStyle = ctx.createPattern(img, 'no-repeat'); 
			//ctx.fill();
		}

	}
	
	function exeAddCorners(img, r){
	
		if(typeof(img.naturalWidth) != "undefined" && img.naturalWidth == 0){
			return false;
		}
		
		r = Math.min(r, $(img).width()/2, $(img).height()/2);
		
		try {
			if($.browser.msie){
				addCornersIE(img, r);
				
			} else if($.browser.safari && !/chrome/.test(navigator.userAgent.toLowerCase()) && isBorderRadiusSupported(img) ) { 
				addCornersCSS(img, r); // с версии 3 Safari нормально закругляет и сглаживает img, Chrome не сглаживает
			
			} else {
				addCorners(img, r);
			}
		} catch(e){}
	}

	$.fn.imgCorners = function(options) {
	
		options = $.extend({
			radius: 10
		}, options ? options : {});

		return this.each(function() {
		
			if(this.complete) {
					exeAddCorners(this, options.radius);
			} else {
				$(this).load(function(){
					exeAddCorners(this, options.radius);
				})
			}

		});
	};
})(jQuery)

