/**
 * Cropper Plugin
 * @author: Azmisov
 * @license: licensed with Eggplant IDE
 * @version: 1.0a
 *
 * img: an image file
 * size: [width, height] dimensions of widget
 * optparams:
 * 		id: unique id reference for
 **/

$('body').extend("cropper",function(img, size, optparams){
	optparams = optparams || {};
	var _p = this;
	//Return the cropper's cropped image
	if (egg.isNum(img) || !egg.isset(img)){
		//Fetch the widget
		img = img || '';
		var img_obj = $('.cropper_widget'+img+' #cropper_img').active();
		if (!img_obj) return false;
		var par = img_obj.parentNode;
		//Get the new image dimensions
		var prop = [
				img_obj.naturalWidth/img_obj.offsetWidth,
				img_obj.naturalHeight/img_obj.offsetHeight,
				par.clientWidth > img_obj.offsetWidth,
				par.clientHeight > img_obj.offsetHeight
			],
			dest = [
				 prop[2] ? img_obj.offsetWidth : par.clientWidth,
				 prop[3] ? img_obj.offsetHeight : par.clientHeight
			],
			src = [
				prop[2] ? 0 : -Math.round($(img_obj).getStyle('left')*prop[0]),
				prop[3] ? 0 : -Math.round($(img_obj).getStyle('top')*prop[1]),
				Math.round(dest[0]*prop[0]),
				Math.round(dest[1]*prop[1])
			];
		//Create the canvas
		var canv = $('.cropper_widget'+img).addChild(true,'canvas',{'width':dest[0],'height':dest[1]},{'display':'none'}).active();
			ctx = canv.getContext('2d');
		ctx.drawImage(img_obj,src[0],src[1],src[2],src[3],0,0,dest[0],dest[1]);
		var img = canv.toDataURL("image/jpeg");
		canv.parentNode.removeChild(canv);
		return img;
	}
	//Create a new widget instance
	if (!_p.isset(window.FileReader) || !_p.isFile(img)){
		alert("please upgrade your browser...");
		return false;
	}
	//Load the image
	else{
		//Supports jpeg,png,bmp,gif
		if (!img.type.match('image/(png|jpeg|bmp|gif)'))
			return alert("Invalid file type");
		var reader = new FileReader();
		reader.onprogress = function(e){
			var p = Math.round((e.loaded / e.total) * 100);
			$("#crop_info").text("Loading image "+p+"%");
		}
		reader.onload = function(e){
			img = e.target.result;
			createHTML();
		}
		reader.readAsDataURL(img);
	}
	//Create the widget's HTML
	var createHTML = function(){
		_p.text('');
		var cust_id = egg.isset(optparams.id) ? optparams.id : '';
		var cont = _p.zen(true,".cropper_widget"+cust_id+">#crop_info{Image Cropper: (drawing image...)}+.cropper_cont>(.cropper_main>img#cropper_img)+.cropper_adjust>.cropper_bar+.cropper_slider").refine('* .cropper_cont');
		cont.style('width',size[0]+"px");
		cont.filter('* .cropper_main').style('height',size[1]+"px");
		cont.filter('* #cropper_img').attr('src',img).imgFire(function(){
			$("#crop_info").text("Image Cropper:");
			//Resize the image to fit the widget (this is size 0%)
			var contDim = [this.parentNode.clientWidth, this.parentNode.clientHeight],
				port = this.naturalHeight/this.naturalWidth > contDim[1]/contDim[0];
			this.epDat.cropper = {};
			var img_dims = this.epDat.cropper.dims = [];
			img_dims[port?1:0] = contDim[port ? 1 : 0];
			img_dims[port?0:1] = (port ? contDim[1]/this.naturalHeight : contDim[0]/this.naturalWidth)*this[port ? 'naturalWidth' : 'naturalHeight'];
			$(this).style({'width':img_dims[0]+"px",'height':img_dims[1]+"px"});
			//Center the image in the frame
			this.epDat.cropper.center = [.5,.5];
			this.style.left = .5*(contDim[0]-img_dims[0])+"px";
			this.style.top = .5*(contDim[1]-img_dims[1])+"px"
			//Register events
			registerEvents(cont);
		});
	}
	//Register widget javascript events
	var registerEvents = function(cont){
		var img_obj = cont.filter('* #cropper_img').active();
		//Zoom slider
		cont.filter('* .cropper_slider').bind('drag',function(e){
			var op = $(this.parentNode).objPos(),
				left = e.pageX-op[0]-e.dragX,
				maxi = this.previousElementSibling.clientWidth-this.offsetWidth;
			if (left>maxi) left = maxi;
			else if (left<0) left = 0;
			this.style.left = left+"px";
			//Adjust image zoom level
			var zoom = Math.round(1000*left/(this.previousElementSibling.clientWidth-this.offsetWidth))/1000,
				img_dims = img_obj.epDat.cropper.dims
				w = (img_obj.naturalWidth-img_dims[0])*zoom+img_dims[0];
				h = (img_obj.naturalHeight-img_dims[1])*zoom+img_dims[1];
			img_obj.style.width = w+"px";
			img_obj.style.height = h+"px";
			//Re-center image (use offset centroid; if smaller than container, use .5)
			var img_cent = img_obj.epDat.cropper.center,
				parDims = [img_obj.parentNode.clientWidth, img_obj.parentNode.clientHeight],
				newOff = [.5*parDims[0]-w*(w>parDims[0]?img_cent[0]:.5),.5*parDims[1]-h*(h>parDims[1]?img_cent[1]:.5)];
			//Normalize the image offset
			if (w>parDims[0]){
				if (newOff[0] > 0) newOff[0] = 0;
				else if (newOff[0]+w < parDims[0]) newOff[0] = parDims[0]-w;
			}
			if (h>parDims[1]){
				if (newOff[1] > 0) newOff[1] = 0;
				else if (newOff[1]+h < parDims[1]) newOff[1] = parDims[1]-h;
			}
			img_obj.style.left = newOff[0]+"px";
			img_obj.style.top = newOff[1]+"px";
		});
		//Image dragger
		cont.filter('* #cropper_img').bind('drag',function(e){
			var obj = $(this),
				newDim = [obj.getStyle('left')+e.mObj[0]-e.dragX, obj.getStyle('top')+e.mObj[1]-e.dragY],
				parDims = [this.parentNode.clientWidth, this.parentNode.clientHeight];
			//Normalize left
			if (this.clientWidth > parDims[0]){
				//left & right side
				if (newDim[0] > 0) newDim[0] = 0;
				else if (newDim[0]+this.clientWidth < parDims[0]) newDim[0] = parDims[0]-this.clientWidth;
				//Set new offset
				this.epDat.cropper.center[0] = (parDims[0]*.5-newDim[0])/this.clientWidth;
				obj.style('left',newDim[0]+'px');
			}
			//Normalize top
			if (this.clientHeight > parDims[1]){
				//top & bottom side
				if (newDim[1] > 0) newDim[1] = 0;
				else if (newDim[1]+this.clientHeight < parDims[1]) newDim[1] = parDims[1]-this.clientHeight;
				//Set new offset
				this.epDat.cropper.center[1] = (parDims[1]*.5-newDim[1])/this.clientHeight;
				obj.style('top',newDim[1]+'px');
			}
		});
	}
});

