/****************************************************
 * Desenvolvido por Leandro Sales
 * leandroasp at gmail dot com
 * +55 86 94275626
 * http://www.leandrosales.com.br
 *
 * Reprodução autorizada desde que mantenha os créditos
 * 
 * BoxImage v1.1.1
 * PhotoCrop v1.2.1
 *
 * Necessário o uso da biblioteca prototype.js 1.5 ou superior.
 *
 * usage: 
 *
 * 1. Usando apenas o BoxImage
 *
 * new LSL.BoxImage(element,{        //this
 *		 e: event, 
 *	   src: 'caminho_da_imagem.jpg', //caminho da imagem
 *	 width: 150, 					 //opcional: largura da imagem a ser exibida
 *	height: 115,					 //opcional: altura da imagem a ser exibida
 *  margin: 5                        //opcional: largura da margem
 * });
 *
 *
 * 2. Usando apenas o PhotoCrop
 *
 * new LSL.PhotoCrop(element, {                    //imagem ou div que contem a imagem
 *			onUpdateCallback: function(cood) {     //opcional
 *				$('input_x').value = cood.x;       //funcao chamada quando as 
 *				$('input_y').value = cood.y;       //coordenadas forem atualizadas
 *				$('input_w').value = cood.width;
 *				$('input_h').value = cood.height;
 *			}, 
 *			aspectRatio: 4/3,                      //opcional: proporcao que a imagem sera cortada
 *			position: {                            //opcional: posicao inicial da marca de corte
 *					 x: $('input_x').value,
 *					 y: $('input_y').value,
 *				 width: $('input_w').value, 
 *				height: $('input_h').value
 *          },
 *			borderColor: '#0000FF', 			   //opcional: cor da borda da selecao
 *			borderWidth: 1, 					   //opcional: grossura da borda da selecao
 *			imgPosition: 'absolute'                //opcional: 
 *	});											   //'relative' quando a posicao da imagem
 *												   //for relativa ao elemento pai
 *												   //'absolute' quando a posicao da imagem
 *												   //for relativa ao documento como um todo
 *												   //OBS: use 'relative' quando usado 
 *												   //junto com BoxImage
 *
 * 3. Usando BoxImage e PhotoCrop
 *
 * new LSL.BoxImage(element,{
 *        e: event, 
 *      src: 'caminho_da_imagem.jpg',
 *    width: 300,
 *   height: 230,
 *   margin: 5,
 * onCreate: function(obj) {
 *		new LSL.PhotoCrop(element, {
 *			onUpdateCallback: function(cood) {
 *				$('input_x').value = cood.x;
 *				$('input_y').value = cood.y;
 *				$('input_w').value = cood.width;
 *				$('input_h').value = cood.height;
 *			}, 
 *			aspectRatio: 4/3,
 *			position: {
 *					 x: $('input_x').value,
 *					 y: $('input_y').value,
 *				 width: $('input_w').value, 
 *				height: $('input_h').value
 *          },
 *			borderColor: '#0000FF',
 *			borderWidth: 1,
 *			imgPosition: 'absolute'
 *		});		
 *   }
 *});
 *
 * ---------------------------------
 * Bugs e Duvidas entre em contato: 
 *   leandroasp at gmail dot com
 * ---------------------------------
 ****************************************************/

var LSL = Class.create();

/**
 * BoxImage v1.1.1
 */
LSL.BoxImage = Class.create();
LSL.BoxImage.prototype = {
  initialize: function(element, opt) {
	if (!opt) opt = {};
	if (!opt.src && !opt.embed) return;
	if (!(element = $(element))) return;
	
	opt.e = opt.e ? opt.e : window.event;
	opt.margin = opt.margin || 5;
	this.onCreate = opt.onCreate || function() {};
	
	var id = element.id + '_' + opt.src.replace(/[^A-Za-z0-9_]/g,'') + '_BOX_IMAGE';
	if ($(id)) return;
	
	var posX = (opt.e.pageX?opt.e.pageX:opt.e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft);
	var posY = (opt.e.pageY?opt.e.pageY:opt.e.clientY+document.body.scrollTop+document.documentElement.scrollTop);
	
	if (opt.src) {
		var ext = opt.src.replace(/^.*\.([a-z0-9_]+)$/i,'$1').toLowerCase();
		var file = opt.src.replace(/^(.*)\.([a-z0-9_]+)$/i,'$1').toLowerCase();

		if (ext == 'swf') {
			opt.width = opt.width || 50;
			opt.height = opt.height || 50;
			$(document.body).insert(
					('<div id="#{id}"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="#{width}" height="#{height}">' +
							'<param name="movie" value="#{src}" />' +
							'<param name="quality" value="high" />' +
							'<embed src="#{src}" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="#{width}" height="#{height}"></embed></object></div>').interpolate({
						id: id,
						src: opt.src,
						width: opt.width,
						height: opt.height
					})
			);
		} else {
			$(document.body).insert(
					('<div id="#{id}"><img src="#{src}" #{width} #{height} alt="" /></div>').interpolate({
						id: id,
						src: opt.src,
						width: (opt.width?'width="' + opt.width + '"':''),
						height: (opt.height?'height="' + opt.height + '"':'')
					})
			);
		}
	} else if (opt.embed) {
		opt.width = opt.width || 50;
		opt.height = opt.height || 50;
		opt.embed = opt.embed.replace(/width=([0-9]+)/g,'width="' + opt.width + '"');
		opt.embed = opt.embed.replace(/height=([0-9]+)/g,'height="' + opt.height + '"');
		$(document.body).insert(
				('<div id="#{id}">#{embed}</div>').interpolate({
					id: id,
					embed: opt.embed
				})
		);
	}

	var div = $(id);
	var img = div.getElementsByTagName('img');
	if (img.length > 0)
		img = $(img[0]);
	else
		img = null;

	div.setStyle({
		position: 'absolute',
		backgroundColor: '#EEEEEE',
		overflow: 'hidden',
		top: '0px',
		left: '0px',
		visibility: 'hidden'
	});
	if (img) {
		img.setStyle({
			position: 'absolute',
			top: opt.margin+'px',
			left: opt.margin+'px'
		});
	}
	
	this.time = null;
	this.id = id;
	this.element = element;

	var mouseout = function(e) {
		clearTimeout(this.time);
		this.time = setTimeout(function() {
			var div = $(this.id);
			if (div && div.parentNode) div.parentNode.removeChild(div);
			this.element.stopObserving('mouseover', mouseout);
			this.element.stopObserving('mouseout', mouseout);
		}.bind(this), 100);
	}.bind(this);

	div.observe('mouseout', mouseout);
	element.observe('mouseout', mouseout);

	div.observe('mouseover', function(e) {
		clearTimeout(this.time);
	}.bind(this));
	element.observe('mouseover', function(e) {
		clearTimeout(this.time);
	}.bind(this));
	
	var timeout;
	var resize = function() {
		if (img && typeof(opt.width) == 'undefined' && (img.getWidth() == 0 || (Prototype.Browser.IE && img.getWidth() < 30))) {
			timeout = setTimeout(resize, 10);
			return;
		}

		opt.width = opt.width || img.getWidth();
		opt.height = opt.height || img.getHeight();

		var maxW = 640;
		var maxH = 480;
		if (opt.width > maxW) {
			opt.height = Math.round(maxW*opt.height/opt.width);
			opt.width = maxW;
		}
		if (opt.height > maxH) {
			opt.width = Math.round(maxH*opt.width/opt.height);
			opt.height = maxH;
		}

		var pos = element.cumulativeOffset();

		posX = parseInt(posX-(opt.width+12)/2);
		posY = (pos.top-opt.height-12);
		
		if (posX < 0) posX = 0;
		if (posY < 0) posY = 0;
		
		div.setStyle({
			top: posY + 'px',
			left: posX + 'px',
			width: (opt.width+opt.margin*2) + 'px',
			height: (opt.height+opt.margin*2) + 'px',
			visibility: 'visible'
		});
		if (img) {
			img.setStyle({
				width: opt.width + 'px',
				height: opt.height + 'px'
			});
			img.width = opt.width;
			img.height = opt.height;
		}
		this.onCreate(this);
	}.bind(this);
	
	var timeout = setTimeout(resize, 1);
	setTimeout(function(){clearTimeout(timeout);}, 2000);
  }
};

/**
 * PhotoCrop v1.2.1
 */
var PhotoCrop_mousemove = function() {};
var PhotoCrop_mouseup = function() {};
LSL.PhotoCrop = Class.create();
LSL.PhotoCrop.prototype = {
  initialize: function(img, opt) {
	img = $(img);
	if (!img) return;

	if (img.tagName.toLowerCase() != 'img') {
		var img = img.getElementsByTagName('img');
		if (img.length > 0) {
			img = $(img[0]);
		} else {
			return;
		}
	}

	this.onMouseDown = this.mousedown.bindAsEventListener(this);
	this.onMouseMove = this.mousemove.bindAsEventListener(this);
	this.onMouseUp = this.mouseup.bindAsEventListener(this);

	this.width = img.offsetWidth;
	this.height = img.offsetHeight;
	this.img = img;
	this.loadOption(opt);
	this.init();
  },
  loadOption: function(opt) {
	if (!opt) opt = {};
	if (!opt.input) opt.input = {};

	opt.input.x = $(opt.input.x);
	opt.input.y = $(opt.input.y);
	opt.input.w = $(opt.input.w);
	opt.input.h = $(opt.input.h);

	this.input = {};
	this.input.x = opt.input.x;
	this.input.y = opt.input.y;
	this.input.w = opt.input.w;
	this.input.h = opt.input.h;
	
	this.aspectRatio = opt.aspectRatio;
	
	this.onUpdateCallback = opt.onUpdateCallback || function() {};
	
	this.borderColor = opt.borderColor || '#0000FF';
	this.borderWidth = opt.borderWidth || 1;
	this.imgPosition = opt.imgPosition;
	
	this.position = opt.position || {};
	this.position.x = this.position.x || 0;
	this.position.y = this.position.y || 0;
	this.position.width = this.position.width || this.width;
	this.position.height = this.position.height || this.height;
  },
  init: function() {
	this.onUpdateCallback(this.position);

	this.div = this.img.id + '_div';
	this.img.insert({
		after: '<div id="' + this.div + '"><div>'
	});
	
	this.div = $(this.div);
	this.imgPos = this.img.cumulativeOffset();
	var imgPos = this.img.cumulativeOffset();
	if (this.imgPosition == 'relative') {
		var divPos = this.img.parentNode.cumulativeOffset();
		imgPos.top -= divPos.top;
		imgPos.left -= divPos.left;
	}
	this.div.setStyle({
		width: this.width + 'px',
		height: this.height + 'px',
		overflow: 'hidden',
		position: 'absolute',
		top: imgPos.top + 'px',
		left: imgPos.left + 'px',
		textIndent: '-1000in',
		zIndex: 100
	});
	
	this.pontilhado = this.div.id + '_p';
	this.div_top = this.div.id + '_top';
	this.div.insert('<div id="' + this.pontilhado + '"></div><div id="' + this.div_top + '"></div>');

	this.div_top = $(this.div_top);
	this.div_top.setStyle({
		backgroundColor: '#FFFFFF',
		filter: 'alpha(opacity=0)',
		MozOpacity: '0',
		opacity: '0',
		position: 'absolute',
		overflow: 'hidden',
		top: '0px',
		left: '0px',
		width: this.width + 'px',
		height: this.height + 'px',
		zIndex: 99,
		cursor: 'crosshair',
		textIndent: '-1000in'
	});

	this.pontilhado = $(this.pontilhado);
	this.pontilhado.setStyle({
		position: 'absolute',
		backgroundColor: '#FFFFFF',
		borderColor: this.borderColor,
		borderStyle: 'dotted',
		borderWidth: this.borderWidth + 'px',
		float: 'left',
		top: this.position.y + 'px',
		left: this.position.x + 'px',
		width: this.position.width-2*this.borderWidth + 'px',
		height: this.position.height-2*this.borderWidth + 'px',
		display: 'block',
		filter: 'alpha(opacity=50)',
		MozOpacity: '0.50',
		opacity: '0.50',
		zIndex: 98,
		textIndent: '-1000in'
	});
	
	this.pontilhadoWidth = $(document.createElement('DIV'));
	this.pontilhadoWidth.setStyle({
		width: this.position.width-2*this.borderWidth + 'px',
		height: this.position.height-2*this.borderWidth + 'px',
		overflow: 'hidden'
	});
	
	this.pontilhado.appendChild(this.pontilhadoWidth);

	this.startOnMouse();
  },
  startOnMouse: function() {
	$(document.body).stopObserving('mousemove', PhotoCrop_mousemove);
	$(document.body).stopObserving('mouseup', PhotoCrop_mouseup);
	PhotoCrop_mousemove = this.onMouseMove;
	PhotoCrop_mouseup = this.onMouseUp;

	this.moveStarted = false;
	var self = this;

	this.div_top.observe('mousedown', this.onMouseDown);
	this.div_top.observe('mouseup', this.onMouseUp);
	this.div.observe('mouseup', this.onMouseUp);

	$(document.body).observe('mousemove', this.onMouseMove);
	$(document.body).observe('mouseup', this.onMouseUp);
  },
  mousedown: function(e) {
	e = e ? e : window.event;
	this.moveStarted = true;

	this.posIniX = (e.pageX ? e.pageX: e.clientX);
	this.posIniY = (e.pageY ? e.pageY: e.clientY);
	
	this.posLeft = (e.layerX ? e.layerX: e.offsetX);
	this.posTop = (e.layerY ? e.layerY: e.offsetY);
	if (!this.posLeft || this.posLeft < 0) this.posLeft = 0;
	if (!this.posTop || this.posTop < 0) this.posTop = 0;

	this.pontilhado.setStyle({
		width: '0px',
		height: '0px',
		display: 'none',
		top: this.posLeft + 'px',
		left: this.posTop + 'px'
	});
	this.pontilhadoWidth.setStyle({
		width: '0px',
		height: '0px'
	});
	
	this.position = {x: 0, y: 0, width: this.width, height: this.height};
	this.onUpdateCallback(this.position);
  },
  mousemove: function(e) {
	if (!this.moveStarted) return;
	e = e ? e : window.event;
	
	var borderWidthIE = 0;
	//if (!Prototype.Browser.IE) borderWidthIE = this.borderWidth;
	borderWidthIE = this.borderWidth;
	
	var newPosX = (e.pageX ? e.pageX: e.clientX);
	var newPosY = (e.pageY ? e.pageY: e.clientY);

	var sizeWidth = newPosX - this.posIniX;
	var sizeHeight = newPosY - this.posIniY;
	var posLeft = this.posLeft;
	var posTop = this.posTop;
	
	if (sizeWidth+posLeft > this.width) sizeWidth = this.width-posLeft;
	if (sizeHeight+posTop > this.height) sizeHeight = this.height-posTop;
	if (sizeWidth+posLeft < 0) sizeWidth = -posLeft;
	if (sizeHeight+posTop < 0) sizeHeight = -posTop;

	if (this.aspectRatio) {
		var p = sizeWidth/sizeHeight;
		p = (p < 0?-p:p);
		if (p > this.aspectRatio) {
			var modW = (sizeWidth < 0?-1:1);
			sizeWidth = Math.round(sizeHeight*this.aspectRatio);
			sizeWidth = modW * (sizeWidth < 0?-sizeWidth:sizeWidth);
		} else if (p < this.aspectRatio) {
			var modH = (sizeHeight < 0?-1:1);
			sizeHeight = Math.round(sizeWidth/(this.aspectRatio));
			sizeHeight = modH * (sizeHeight < 0?-sizeHeight:sizeHeight);
		}
	}

	if (sizeWidth < 0) {
		sizeWidth = -sizeWidth;
		posLeft -= sizeWidth;
		if (posLeft < 0) {
			sizeWidth += posLeft;
			posLeft = 0;
		}
	} else {
		sizeWidth -= 2*borderWidthIE;
		if (sizeWidth < 0) sizeWidth = 0;
	}
	if (sizeHeight < 0) {
		sizeHeight = -sizeHeight;
		posTop -= sizeHeight;
		if (posTop < 0) {
			sizeHeight += posTop;
			posTop = 0;
		}
	} else {
		sizeHeight -= 2*borderWidthIE;
		if (sizeHeight < 0) sizeHeight = 0;
	}

	if (posLeft+sizeWidth > (this.width-2*borderWidthIE)) sizeWidth = this.width-2*borderWidthIE-posLeft;
	if (posTop+sizeHeight > (this.height-2*borderWidthIE)) sizeHeight = this.height-2*borderWidthIE-posTop;

	this.pontilhado.setStyle({
		width: sizeWidth + 'px',
		height: sizeHeight + 'px',
		left: posLeft + 'px',
		top: posTop + 'px',
		display: 'block'
	});
	this.pontilhadoWidth.setStyle({
		width: sizeWidth + 'px',
		height: sizeHeight + 'px'
	});
	
	this.position = {x: posLeft, y: posTop, width: sizeWidth+2*borderWidthIE, height: sizeHeight+2*borderWidthIE};
	this.onUpdateCallback(this.position);
  },
  mouseup: function() {
	if (!this.moveStarted) return;
	this.onUpdateCallback(this.position);
	this.moveStarted = false;
  }
};