/*
 * @autor Felipe Marques
 * @date 21-01-2010
 *
 * @namespace MRP
*/
var MRP = {}; // inicio do namespace

/*
 * A maioria das variaveis deste objeto estao sendo atribuidas atraves do arquivo config.php da raiz do gerenciador
 * no arquivo topo.php dentro da pasta de recursos este config.php é chamada atraves de uma tag como se fosse
 * um arquivo javascript
*/
MRP.Config = {};

/*
 * @Declaração de variaveis do objeto principal MRP
*/
MRP.timeout = 0;

/*
 * @autor Felipe Marques
 * @date 22-04-2010
 *
 * @method Event
 * @access public
 * @params variable
 * @return boolean
*/
MRP.Loader = new Object(
{
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 22-04-2010
	 *
	 * @method 
	 * @access 
	 * @params 
	 * @return 
	*/
	padrao: function(callback)
	{
		var loaderModulo = new YAHOO.util.YUILoader(
		{
			require: [
				'animation',
				'button',
				'calendar',
				'container',
				'colorpicker',
				'dom',
				'datatable',
				'datasource',
				'dragdrop',
				'editor',
				'element',
				'event',
				'json',
				'menu',
				'paginator',
				'tabview',
				'uploader',
				'connection'
			], 
			base: 'recursos/yui/build/',
			loadOptional: false,
			onSuccess: function() 
			{
				if(callback != '' && callback != undefined && callback != null)
				{
					callback();
				}
				else
				{
					try
					{
						MODULO.Carregar();
					}
					catch(e)
					{
						alert('É necessário ao menos especificar um método para carregamento do módulo.')	
					}
				}
			},
			onFailure: function(o) 
			{
				alert("Erro carregando bibliotecas: \n" + YAHOO.lang.dump(o));
			}
		});
		
		// insere no corpo do html os javascripts carregados     
		loaderModulo.insert();
	},

	/*
	 * @autor Felipe Marques
	 * @date 22-04-2010
	 *
	 * @method 
	 * @access 
	 * @params 
	 * @return 
	*/
	personalizado: function(config,callback)
	{
		if(config.requires == null || config.requires == undefined)
		{
			alert('Para utilizar o loader personalizado, especifique os recursos a serem carregados.');
			return false;
		}
		
		if(config.base == null || config.base == undefined || config.base == '')
		{
			alert('É necessário informar o o path para o load dos recursos');	
			return false;
		}
		
		if(config.loadOptional == null || config.loadOptional == undefined || config.loadOptional == '')
		{
			config.loadOptional = false;
		}
		
		var loaderModulo = new YAHOO.util.YUILoader(
		{
			require: config.requires, 
			base: config.base,
			loadOptional: config.loadOptional,
			onSuccess: function() 
			{
				if(callback != '' && callback != undefined && callback != null)
				{
					callback();
				}
				else
				{
					try
					{
						MODULO.Carregar();
					}
					catch(e)
					{
						alert('É necessário ao menos especificar um método para carregamento do módulo.')	
					}
				}
			},
			onFailure: function(o) 
			{
				alert("Erro carregando bibliotecas: \n" + YAHOO.lang.dump(o));
			}
		});
		
		// insere no corpo do html os javascripts carregados     
		loaderModulo.insert();
	}
});

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method Event
 * @access public
 * @params variable
 * @return boolean
*/
MRP.Carregando = function(nome,opcoes, callback)
{
	// ok
	if(opcoes == undefined) opcoes = [];
	
	var win = new YAHOO.widget.Panel(nome, {
		modal: opcoes['modal'] || true,
		fixedcenter: opcoes['fixedcenter'] || true,
		draggable: opcoes['draggable'] || false,
		width: opcoes['width'] || '300px',
		height: opcoes['height'],
		zindex: 4,
		visible : opcoes['visible'] || true, 
		constraintoviewport : opcoes['cosntraintviewport'] || false,
		close: opcoes['close'] || false							
	});

	win.setHeader((opcoes['header'] || "Carregando, aguarde..."));
	win.setBody(opcoes['body'] || "<div align=\'center\'><br><img src=\'recursos/imagens/loading.gif\' /></div><br>");
	win.render(document.body);		

	if(opcoes['timeout'] != '' && opcoes['timeout'] != undefined)
		setTimeout(function(){win.hide();},parseInt(opcoes['timeout']));

	if(callback != '' && callback != undefined && callback != null) 
		callback(win);

	return win;
}

/*
 * @autor Felipe Marques
 * @date 18-01-2010
 *
 * @method 
 * @access 
 * @params 
 * @return 
*/
MRP.Tab = new Object(
{
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 22-03-2010
	 *
	 * @return boolean
	*/
	tabs:null,
	
	/*
	 * @autor Felipe Marques
	 * @date 22-03-2010
	 *
	 * @return boolean
	*/
	init: function(obj,titulo,url,callback,fecharTudo)
	{
		try
		{
			this.tabs = new YAHOO.widget.TabView(obj);
			
			if(fecharTudo == undefined || fecharTudo == null || fecharTudo == '' || fecharTudo != false ) this.FecharAbas();
			
			if(MRP.isUrl(url))
			{
				this.tabs.addTab( new YAHOO.widget.Tab({
					label: titulo, // titulo da modal
					href: 'abaNovoTexto',
					dataSrc: url, // url para acesso aos dados via ajax
					cacheData: true,
					active: true
				}));

				if(callback != undefined && callback != '')
				{
					var tabAtiva = this.tabs.get('activeTab');
					tabAtiva.addListener('beforeDataLoadedChange', callback);
				}
			}
			else
			{
				if(url == undefined) url = null;
				
				this.tabs.addTab( new YAHOO.widget.Tab({
					label: titulo, // titulo da modal
					content:url,
					href: 'abaNovoTexto',
					active: true
				}));
				
				if(callback != undefined && callback != '')
				{
					var tabAtiva = this.tabs.get('activeTab');
					callback(tabAtiva);
				}
			}
			
		}
		catch(e)
		{
			console.log(e);	
		}
		
		return this.tabs;
	},

	/*
	 * @autor Felipe Marques
	 * @date 21-01-2010
	 *
	 * @method FecharAbas
	 * @access public
	 * @params pagina,coluans,colunas_resultado
	 * @return null
	*/
	addTab: function(titulo,opcoes,callback,fecharTudo)
	{
		var tabView = this.tabs;
		
		if(fecharTudo == undefined || fecharTudo == null || fecharTudo == '' || fecharTudo != false ) this.FecharAbas(fecharTudo);
		
		tabView.addTab( new YAHOO.widget.Tab({
			label: titulo, // titulo da modal
			content: opcoes.content || null,
			dataSrc: opcoes.dataSrc || null,
			href: opcoes.href || 'abaNova',
			active: true
		}));
		
		if(callback != undefined && callback != '')
		{
			var tabAtiva = this.tabs.get('activeTab');
			callback(tabAtiva);
		}

	},
	
	/*
	 * @autor Felipe Marques
	 * @date 21-01-2010
	 *
	 * @method FecharAbas
	 * @access public
	 * @params pagina,coluans,colunas_resultado
	 * @return null
	*/
	FecharAbas: function(href)
	{
		var tabs = this.tabs.get('tabs');
		var filtro = href || 'abaNovoTexto';
		
		for (var i = 0; i < tabs.length; i++) 
		{	
			if(String(tabs[i].get('href')) == filtro) 
			{
				this.tabs.removeTab(tabs[i]); 
				break;
			}
		}
	}
});

/*
 * @autor Felipe Marques
 * @date 22-03-2010
 *
 * @namespace object
*/
MRP.Modal = new Object();

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @return 
*/
MRP.Modal.container = function(id,opcoes, callback)
{
	// ok
	try
	{
		if(opcoes == undefined) opcoes = [];
		
		var win = new YAHOO.widget.Panel(id, {
			modal: opcoes['modal'] || true,
			fixedcenter: opcoes['fixedcenter'] || true,
			draggable: opcoes['draggable'] || true,
			width: opcoes['width'] || '300px',
			height: opcoes['height'],
			visible : opcoes['visible'] || false, 
			constraintoviewport : opcoes['cosntraintviewport'] || true,
			close: opcoes['close'] || true							
		});
	
		win.setHeader((opcoes['header'] || "Painel"));
		win.setBody(opcoes['body'] || "Nenhum texto no corpo do painel.");
		win.render(document.body);
	
		if(opcoes['show']) 
			win.show();
	
		if(opcoes['onclose'] != '' && opcoes['onclose'] != undefined) 
			win.beforeHideEvent.subscribe(opcoes['onclose']);
	
		if(callback != '' && callback != undefined && callback != null) 
			callback(win);
	
		try
		{
			var idpanelmodal = MRP.Get(id+'_mask','id');
				idpanelmodal.title = 'Clique aqui para fechar!';
			
			MRP.Event(idpanelmodal.id,'click',function(){
				win.hide();												   
			});
		}
		catch(e)
		{
		
		}
	}
	catch(ex)
	{
		console.log(id);
		alert(ex);	
	}

	return win;
}

/*
 * @autor Felipe Marques
 * @date 22-03-2010
 *
 * @return boolean
*/
MRP.Modal.html = function(id,opcoes)
{
	// ok
	// Este eh o id do elemento que esta no html da pagina, onde o YUI ira renderizar o modal
	var elemento = id;
	var largura = opcoes['largura'];
	var panel = null;
	
	// Metodos para Fixar o Tamanho da Modal e centralizando-a
	var fixResize = function() 
	{ 
		var thisX = ( parseInt((YAHOO.util.Dom.getClientWidth()- largura)/2) );
		if (thisX<0) thisX=0;
		YAHOO.example.dialog1.cfg.setProperty('x', thisX); 
	}
	
	// seta o mtodo como Evento ouvinte 
	YAHOO.util.Event.addListener(window, 'resize', fixResize);
	
	// pega a coordenada X (horizontal) da janela
	var thisX = (parseInt((YAHOO.util.Dom.getClientWidth()- largura)/2));
	
	// tenta destruir o objeto dialo1
	try 
	{ 
		YAHOO.example.dialog1.destroy();
		MRP.Editor.myEditor.destroy();
	}
	catch(e){}

	// Instancia um nobo Objeto Dialog1
	YAHOO.example.dialog1 = new YAHOO.widget.Panel(elemento, 
	{ 
		xy:[thisX,10],
		width : largura+"px",
		fixedcenter : false,
		visible : false, 
		constraintoviewport : true,
		close: true 
	});

	// renderiza o modal
	YAHOO.example.dialog1.render(document.body);
	YAHOO.example.dialog1.show();

	try
	{
		var idpanelmodal = MRP.Get(id+'_mask','id');
			idpanelmodal.title = 'Clique aqui para fechar!';
		
		MRP.Event(idpanelmodal.id,'click',function(){
			win.hide();												   
		});
	}
	catch(e)
	{
	
	}

	if(opcoes['onclose'] != '' && opcoes['onclose'] != undefined)
		YAHOO.example.dialog1.beforeHideEvent.subscribe(opcoes['onclose']);
}

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method Event
 * @access public
 * @params variable
 * @return boolean
*/
MRP.DragDrop = function(callback,callback_endDrag)
{
	var Dom = YAHOO.util.Dom;
	var Event = YAHOO.util.Event;
	var DDM = YAHOO.util.DragDropMgr;
	
	YAHOO.example.DDApp = 
	{
		init: function()
		{
			if(callback != '' && callback != undefined)
			{
				callback();
			}
			else
			{
				alert('Error callback!');
			}
			
		}
		,
		showOrder: function()
		{
			var parseList = function(ul, title) 
			{
				var items = ul.getElementsByTagName("div");
				var out = title + ": ";
				
				for (i=0;i<items.length;i=i+1) 
				{
					out += items[i].id + " ";
				}
				
				return out;
			};
	
			try
			{
				var ul1=Dom.get("corpo1"), ul2=Dom.get("corpo2");
				alert(parseList(ul1, "List 1") + "\n" + parseList(ul2, "List 2"));
			}
			catch(e)
			{
				
			}
	
		},
		switchStyles: function() 
		{
			Dom.get("corpo1").className = "draglist_alt";
			Dom.get("corpo2").className = "draglist_alt";
		}
	}
	
	//////////////////////////////////////////////////////////////////////////////
	// custom drag and drop implementation
	//////////////////////////////////////////////////////////////////////////////
	YAHOO.example.DDList = function(id, sGroup, config) 
	{
	
		YAHOO.example.DDList.superclass.constructor.call(this, id, sGroup, config);
	
		this.logger = this.logger || YAHOO;
		var el = this.getDragEl();
		Dom.setStyle(el, "opacity", 0.67); // The proxy is slightly transparent
	
		this.goingUp = false;
		this.lastY = 0;
	};
	
	YAHOO.extend(YAHOO.example.DDList, YAHOO.util.DDProxy, {
	
		startDrag: function(x, y) 
		{
			this.logger.log(this.id + " startDrag");
	
			// make the proxy look like the source element
			var dragEl = this.getDragEl();
			var clickEl = this.getEl();
			Dom.setStyle(clickEl, "visibility", "hidden");
			
			if(!navigator.appName.match(/Internet Explorer/i))
			{
				//console.log(clickEl.innerHTML.replace(/(id\=\")/gi,'id="@@hack@@'))
				var html = clickEl.innerHTML.replace(/(id\=\")/gi,'id="@@hack@@');
					html = html.replace(/(<div[ ])/gi,'<div id="@@div-hack@@'+clickEl.id+'" ');
				
				//try{console.log(html);}catch(e){}
				dragEl.innerHTML = html;
				dragEl.style.padding = "5px 5px 5px 5px";
				dragEl.style.display = "block";
			}

			Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
			Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
			Dom.setStyle(dragEl, "border", "2px solid gray");
		},
	
		endDrag: function(e) 
		{

			var srcEl = this.getEl();
			var proxy = this.getDragEl();
			
			// Show the proxy element and animate it to the src element's location
			Dom.setStyle(proxy, "visibility", "");
			var a = new YAHOO.util.Motion( 
				proxy, { 
					points: { 
						to: Dom.getXY(srcEl)
					}
				}, 
				0.2, 
				YAHOO.util.Easing.easeOut 
			)
			var proxyid = proxy.id;
			var thisid = this.id;
			
			// Hide the proxy and show the source element when finished with the animation
			a.onComplete.subscribe(function(){
				Dom.setStyle(proxyid, "visibility", "hidden");
				Dom.setStyle(thisid, "visibility", "");
			});
			a.animate();
			
			if(callback_endDrag != '' && callback_endDrag != undefined) callback_endDrag();

		},
	
		onDragDrop: function(e, id) 
		{
			// If there is one drop interaction, the li was dropped either on the list,
			// or it was dropped on the current location of the source element.
			if (DDM.interactionInfo.drop.length === 1) {
	
				// The position of the cursor at the time of the drop (YAHOO.util.Point)
				var pt = DDM.interactionInfo.point; 
	
				// The region occupied by the source element at the time of the drop
				var region = DDM.interactionInfo.sourceRegion; 
	
				// Check to see if we are over the source element's location.  We will
				// append to the bottom of the list once we are sure it was a drop in
				// the negative space (the area of the list without any list items)
				if (!region.intersect(pt)) 
				{
					var destEl = Dom.get(id);
					var destDD = DDM.getDDById(id);
					destEl.appendChild(this.getEl());
					destDD.isEmpty = false;
					DDM.refreshCache();
				}
	
			}
		},
	
		onDrag: function(e)
		{
			// Keep track of the direction of the drag for use during onDragOver
			var y = Event.getPageY(e);
	
			if (y < this.lastY) 
			{
				this.goingUp = true;
			}
			else if (y > this.lastY) 
			{
				this.goingUp = false;
			}
	
			this.lastY = y;
		},
	
		onDragOver: function(e, id) 
		{
			var srcEl = this.getEl();
			var destEl = Dom.get(id);
	
			// We are only concerned with list items, we ignore the dragover
			// notifications for the list.
			if (destEl.nodeName.toLowerCase() == "div") 
			{
				var orig_p = srcEl.parentNode;
				var p = destEl.parentNode;
	
				if (this.goingUp) 
				{
					p.insertBefore(srcEl, destEl); // insert above
				}
				else
				{
					p.insertBefore(srcEl, destEl.nextSibling); // insert below
				}
	
				DDM.refreshCache();
			}
		}
	});
	Event.onDOMReady(YAHOO.example.DDApp.init, YAHOO.example.DDApp, true);
}

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method Event
 * @access public
 * @params variable
 * @return boolean
*/
MRP.Event = function(elemento,evento,callback,debug)
{
	if(debug)
	{
		try
		{
			console.log('------------------------'+elemento+'------------------------------');
			console.log('getListeners: '+YAHOO.util.Event.getListeners(elemento));
			console.log('getEvent: '+YAHOO.util.Event.getEvent(elemento,evento));
			console.log('------------------------'+elemento+'------------------------------');
		}
		catch(e)
		{
			alert(e);	
		}
	}
	
	if(MRP.DOM.isArray(evento))
	{
		for(var i = 0; i < evento.length; i++)
			YAHOO.util.Event.addListener(elemento, evento[i], callback);
	}
	else
	{
		YAHOO.util.Event.addListener(elemento, evento, callback);
	}
}

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method Event
 * @access public
 * @params variable
 * @return boolean
*/
MRP.EventRemove = function(elemento,evento,debug)
{
	if(debug)
	{
		try
		{
			console.log('------------------------'+elemento+'------------------------------');
			console.log('getListeners: '+YAHOO.util.Event.getListeners(elemento));
			console.log('getEvent: '+YAHOO.util.Event.getEvent(elemento,evento));
			console.log('------------------------'+elemento+'------------------------------');
		}
		catch(e)
		{
			alert(e);	
		}
	}
	
	if(MRP.DOM.isArray(evento))
	{
		for(var i = 0; i < evento.length; i++)
		{
			YAHOO.util.Event.removeListener(elemento, evento[i]);
		}
	}
	else
	{
		YAHOO.util.Event.removeListener(elemento, evento);
	}
}

/*
 * @autor Felipe Marques
 * @date 18-01-2010
 *
 * @method ButtonHTML
 * @access public
 * @params variable
 * @return boolean
*/
MRP.ButtonHTML = function(id_html,evento,callback)
{
	// ok
	var btCriarNovo = new YAHOO.widget.Button(id_html);
	
	if(callback == '' || typeof(callback) == "undefined")
	{
		callback = function(){}	
	}
	
	if(evento != '')
	{
		YAHOO.util.Event.on(id_html, evento, callback);
	}	
}

/*
 * @autor Felipe Marques
 * @date 18-01-2010
 *
 * @method Button
 * @access public
 * @params variable
 * @return boolean
*/
MRP.Button = function(titulo,id,container,evento,callback)
{
	// ok
	// Instancia novo Boto
	var btAtualizarTexto = new YAHOO.widget.Button({label:titulo, id:id, container:container });
	
	if(callback == '' || typeof(callback) == "undefined")
	{
		callback = function(){}	
	}
	
	if(evento != '')
	{
		YAHOO.util.Event.on(id, evento, callback);
	}	
}

/*
 * @autor Felipe Marques
 * @date 18-01-2010
 *
 * @method 
 * @access 
 * @params 
 * @return 
*/
MRP.HTML = new Object(
{
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 18-01-2010
	 *
	 * @method 
	 * @access 
	 * @params 
	 * @return 
	*/
	create: function(obj,id,classe)
	{
		var el = document.createElement(obj);
			el.id = id;
		
		new YAHOO.util.Element(el).addClass(classe);
			
		return el;
	},
	
	/*
	 * @autor Felipe Marques
	 * @date 18-01-2010
	 *
	 * @method addClass
	 * @access public
	 * @params variable
	 * @return boolean
	*/
	addClass: function(obj,classe)
	{
		new YAHOO.util.Element(obj).addClass(classe);
	}
});
	
/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method 
 * @access 
 * @params 
 * @return 
 * @desc
*/
MRP.Ajax = function(method,url,callback,postData)
{
	// ok
	if(callback == '' || callback == undefined)
	{
		var handleSubmit = {
			success:function(args)
			{					
				alert('Response 200 OK: \n'+args.responseText);
			},
			failure:function(args)
			{
				alert(args.responseText);
			}
		};
	}
	else
	{
		var handleSubmit = callback;	
	}
	
	if(method == 'POST')
	{
		YAHOO.util.Connect.asyncRequest(method, url, handleSubmit, postData);			
	}
	else if(method == 'GET')
	{
		YAHOO.util.Connect.asyncRequest(method, url, handleSubmit);				
	}
	
	return this;
}

/*
 * @autor Felipe Marques
 * @date 18-01-2010
 *
 * @method Submit
 * @access public
 * @params 
 * @return 
 * @desc
*/
MRP.Submit = function(form,url,callback,handle,postData,saveEditor)
{
	// Por padrao , sempre ao darmos o submit ele ira salvar os dados do Editor,
	// porem se estiver setado algum valor para saveEditor o mesmo nao sera salvo
	if(saveEditor == undefined || saveEditor == '')
	{
		/*
		 * Para cada submit tentamos salvar os dados do editor
		*/
		try{ MRP.Editor.SaveEditor(); }catch(e){}
	}
	
	if(!typeof(opcoes) == 'object')
	{
		handleSubmit = handle;
	}
	else
	{
		handleSubmit = 
		{
			success:function(args)
			{					
				if(callback != null && callback != undefined && callback != '')
				{
					callback(args);	
				}
			},
			failure:function(args)
			{
				alert(args.responseText);
			}
		};
	}
		
	YAHOO.util.Connect.setForm(form, false);
	YAHOO.util.Connect.asyncRequest('POST', url, handleSubmit, postData);
}

/*
 * @autor Felipe Marques
 * @date 13-04-2010
 *
 * @method Upload
 * @access 
 * @params 
 * @return 
 * @desc
*/
MRP.Upload = function(formObject,url,handler,callback,postData)
{
	// ok
	if(handler != '' && handler != undefined && handler != null)
	{
		this.uploadHandler = handler;
	}
	else
	{
		this.uploadHandler = {
			upload:function(data)
			{
				if(callback != null && callback != undefined && callback != '')
				{
					callback(data);	
				}
			},
			failure:function(data)
			{
				alert(data.responseText);
			}
		};
	}

	YAHOO.util.Connect.setForm(formObject, true, true); // true para envio de arquivo multi-part-form-data
	YAHOO.util.Connect.asyncRequest('POST', url, this.uploadHandler,postData);			
}

/*
 * @autor Felipe Marques
 * @date 21-01-2010
 *
 * @method DataTable
 * @access public
 * @params pagina,coluans,colunas_resultado
 * @return null
*/
MRP.DataTable = new Object();
MRP.DataTable.myColumnDefs = '';
MRP.DataTable.colunas_resultado = '';
MRP.DataTable.oConfigs = '';
MRP.DataTable.myDataTable = '';
MRP.DataTable.myDataSource = '';
MRP.DataTable.linhasPorPagina = 15;
MRP.DataTable.container = ['below'];
MRP.DataTable.paginacao = 'paginated';

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method DataTable.init
 * @access 
 * @params 
 * @return 
*/
MRP.DataTable.addColuna = function(opcao,coluna)
{
	if( !MRP.DOM.isArray(opcao) )
	{
		if(opcao == 'inicio')
		{
			// ex: MRP.DataTable.addColuna('inicio',{key:"@", minWidth: 20, formatter:"compartilhadoFormat"});
			this.myColumnDefs.unshift(coluna);		
		}
		else if(opcao == 'fim')
		{
			// ex: MRP.DataTable.addColuna('fim',{key:"@", minWidth: 20, formatter:"compartilhadoFormat"});
			this.myColumnDefs.push(coluna);
		}
	}
	else
	{
		// ex: MRP.DataTable.addColuna(['antes','nm'],{key:"@", minWidth: 20, formatter:"compartilhadoFormat"});
		if(opcao[0] == 'antes')
		{
			var temp = new Array();
			
			for(var i = 0; i < this.myColumnDefs.length; i++)
			{
				if(this.myColumnDefs[i].key == opcao[1])
				{
					temp.push(coluna);					
				}

				temp.push(this.myColumnDefs[i]);

			}
			
			this.myColumnDefs = temp;
		}
		else if(opcao[0] == 'depois')
		{
		// ex: MRP.DataTable.addColuna(['depois','id'],{key:"@", minWidth: 20, formatter:"compartilhadoFormat"});

			var temp = new Array();
			
			for(var i = 0; i < this.myColumnDefs.length; i++)
			{
				temp.push(this.myColumnDefs[i]);
				
				if(this.myColumnDefs[i].key == opcao[1])
				{
					temp.push(coluna);					
				}
			}
			
			this.myColumnDefs = temp;
		}
	}
}

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method DataTable.init
 * @access 
 * @params 
 * @return 
*/
MRP.DataTable.config = function(pagina,colunas,colunas_resultado)
{
	// ok
	this.myColumnDefs = colunas;	
	this.myDataSource = new YAHOO.util.DataSource(pagina);
	this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
	
	this.colunas_resultado = colunas_resultado
	
	this.myDataSource.responseSchema = {
		resultsList: "records",
		fields: this.colunas_resultado
	};
	
	this.oConfigs = {
			MSG_EMPTY : "Nenhum registro foi localizado.",
			MSG_ERROR : "Erro no acesso as informações.",
			MSG_LOADING : "Carregando registros. Aguarde.", 
			paginator: new YAHOO.widget.Paginator({
				rowsPerPage: this.linhasPorPagina || 15,
				firstPageLinkLabel: "Primeira",
				previousPageLinkLabel: "Prev",
				nextPageLinkLabel: "Prox",
				lastPageLinkLabel: "&Uacute;ltima",
				containers : this.container
			})
	};
}

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method DataTable.init
 * @access 
 * @params 
 * @return 
*/
MRP.DataTable.init = function(paginacao)
{
	// ok
	var id = (paginacao || this.paginacao || 'paginated');

	//try{ this.myDataTable.destroy(); }catch(e){}

	this.myDataTable = new YAHOO.widget.DataTable(id, this.myColumnDefs, this.myDataSource, this.oConfigs);		
	this.myDataTable.subscribe("rowMouseoverEvent", this.myDataTable.onEventHighlightRow);
	this.myDataTable.subscribe("rowMouseoutEvent", this.myDataTable.onEventUnhighlightRow);
}

/*
 * @autor Felipe Marques
 * @date 25-01-2010
 *
 * @method DataTable.Formatter
 * @access 
 * @params 
 * @return 
*/
MRP.DataTable.Formatter = function(nome_formatador, metodo)
{
	// ok
	var conteudo = '';
	conteudo += 'this.'+nome_formatador+' = '+metodo+';\n';
	conteudo += 'YAHOO.widget.DataTable.Formatter.'+nome_formatador+' = this.'+nome_formatador+';';
	eval(conteudo);
}

/*
 * @autor Felipe Marques
 * @date 07-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.DataTable.Simples = function(opcoes)
{
	// ok
	var id = opcoes['id'];
	var container = opcoes['container'];
	var datasource = opcoes['datasource'];
	var colunas = opcoes['colunas'];
	var colunas_resultado = opcoes['colunas_resultado'];
	var linhasPorPagina = opcoes['linhasPorPagina'];

	MRP.DataTable.linhasPorPagina = linhasPorPagina;
	MRP.DataTable.container = container;
	MRP.DataTable.paginacao = id;
	MRP.DataTable.config(datasource,colunas,colunas_resultado);
	
	/*
	 * Configura os formatadores do DataTable
	*/
	MRP.DataTable.Formatter('alterarFormat', function(elLiner, myDataSource, oColumn, oData){
		var id = myDataSource.getData("id");
		var bt = 'btFormatadorAlterar'+id;
		var html = '<img id="'+bt+'" src="recursos/imagens/ico_edit.gif" title="Alterar"/>';
		elLiner.innerHTML = html;
		
		if(oColumn.callback != undefined && oColumn.callback != '') oColumn.callback(bt,id);
	});

	MRP.DataTable.Formatter('excluirFormat', function(elLiner, myDataSource, oColumn, oData){
		var id = myDataSource.getData("id");
		var bt = 'btFormatadorExcluir'+id;
		var html = '<img id="'+bt+'" src="recursos/imagens/ico_trash.gif" title="Excluir"/>';
		elLiner.innerHTML = html;

		if(oColumn.callback != undefined && oColumn.callback != '') oColumn.callback(bt,id);
	});
	
	MRP.DataTable.init(id);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor = new Object();
MRP.Editor.myEditor = null;
MRP.Editor.config = new Array();
MRP.Editor.Toolbar = new Object({editor:MRP.Editor,widgets: new Array()});
MRP.Editor.Widget = new Object({editor:MRP.Editor});

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setFontFamilySize = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{ group: 'fontstyle', label: 'Fonte e Tamanho',
			buttons: [
				{ type: 'select', label: 'Arial', value: 'fontname', disabled: true,
					menu: [
						{ text: 'Arial', checked: true },
						{ text: 'Arial Black' },
						{ text: 'Comic Sans MS' },
						{ text: 'Courier New' },
						{ text: 'Lucida Console' },
						{ text: 'Tahoma' },
						{ text: 'Times New Roman' },
						{ text: 'Trebuchet MS' },
						{ text: 'Verdana' }
					]
				},
				{ type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true }
			]
		}
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setFontType = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{ group: 'parastyle', label: 'Tipo da Fonte',
			buttons: [
				{ type: 'select', label: 'Normal', value: 'heading', disabled: true,
					menu: [
						{ text: 'Texto Normal', value: 'none', checked: true },
					//	{ text: 'T&iacute;tulo', value: 'h1' },
						{ text: 'Sub-t&iacute;tulo', value: 'h2' },
						{ text: 'Chamada', value: 'h3' },
						{ text: 'Coment&aacute;rio', value: 'h4' },
						{ text: 'Pequeno', value: 'h5' },
						{ text: 'Mini', value: 'h6' },
						{ text: 'Pre-Formatado', value: 'pre' }
					]
				}, 
				{ type: 'separator' }
			]
		}
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setFontStyle = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{ group: 'textstyle', label: 'Estilo da fonte',
				buttons: [
					{ type: 'push', label: 'Negrito', value: 'bold' },
					{ type: 'push', label: 'Italico', value: 'italic' },
					{ type: 'push', label: 'Sublinhado', value: 'underline' },
					{ type: 'separator' },
					{ type: 'color', label: 'Cor da Fonte', value: 'forecolor', disabled: true },
					{ type: 'color', label: 'Cor de Fundo', value: 'backcolor', disabled: true }
				]
			},
			 { group: 'textstyle', label: 'Sub/Sobres.',
				buttons: [					
					{ type: 'push', label: 'Subscrito', value: 'subscript', disabled: true },
					{ type: 'push', label: 'Sobrescrito', value: 'superscript', disabled: true },
					{ type: 'separator' }
				]
		}
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setTextStyle = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{ group: 'textstyle', label: 'Cor',
			buttons: [
				{ type: 'color', label: 'Cor da Fonte', value: 'forecolor', disabled: true },
				{ type: 'color', label: 'Background Color', value: 'backcolor', disabled: true },
				{ type: 'separator' }
			]
		}
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setAlignment = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{ group: 'alignment', label: 'Alinhamento',
			buttons: [
				{ type: 'push', label: 'Alinhar a esquerda CTRL + SHIFT + [', value: 'justifyleft' },
				{ type: 'push', label: 'Centralizar Center CTRL + SHIFT + |', value: 'justifycenter' },
				{ type: 'push', label: 'Alinhar a direita  CTRL + SHIFT + ]', value: 'justifyright' },
				{ type: 'push', label: 'Justificar', value: 'justifyfull' }
			]
		}
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setIndentList = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{
		 group: 'indentlist',
			label: 'Listas',
			buttons: [
				{ type: 'push', label: 'Indent', value: 'indent', disabled: true },
				{ type: 'push', label: 'Outdent', value: 'outdent', disabled: true },
				{ type: 'push', label: 'Criar lista sem ordenao', value: 'insertunorderedlist' },
				{ type: 'push', label: 'Criar lista ordenanda', value: 'insertorderedlist' },
				{ type: 'separator' }
			]	
		}
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setControlFormat = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{ group: 'textstyle', label: 'Controle de Formata&ccedil;&atilde;o',
			buttons: [
				{ type: 'push', label: 'Novo parágrafo', value: 'insertparagraph' },
				/*{ type: 'push', label: 'Destacar campos', value: 'hiddenelements' },*/
				{ type: 'push', label: 'Remover Formatacao', value: 'removeformat', disabled: true },
				{ type: 'push', label: 'Apagar todo texto', value: 'clearAll'},
				{ type: 'push', label: 'Editar HTML', value: 'editcode' },
				{ type: 'separator' }
			]
		}	
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setInsertItem = function()
{
	// ok
	this.editor.config.toolbar.buttons.push(
		{ group: 'insertitem', label: 'Inserir',
			buttons: [
				{ type: 'push', label: 'Inserir Link', value: 'createlink', disabled: true },							
				/*{ type: 'push', label: 'Inserir Imagem2', value: 'insertimage' },*/
				{ type: 'push', label: 'Inserir Imagem', value: 'insertFoto' },
				/*{ type: 'push', label: 'Inserir Tabela', value: 'inserttable' },*/
				/*{ type: 'push', label: 'Inserir Widget', value: 'insertwidget' },*/
				{ type: 'push', label: 'Inserir Link de Arquivo', value: 'insertfile' },
				{ type: 'separator' }
			]
		}	
	);
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setGrupo = function(grupos)
{
	// ok
	for(var i = 0; i < grupos.length; i++)
	{
		try
		{
			//console.log('MRP.Editor.Toolbar.'+grupos[i]+'();');
			eval('MRP.Editor.Toolbar.'+grupos[i]+'();');
		}
		catch(e){}
	}	
}

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.setAll = function()
{
	// ok
	this.setFontFamilySize();
	this.setFontType();
	this.setFontStyle();
	this.setTextStyle();
  	this.setAlignment();
	this.setIndentList();
	this.setControlFormat();
	this.setInsertItem();
}

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Toolbar.on = function()
{
	// ok
	// percorre as definicoes dos botoes e procura pelos seus metodos
	// 1º Percorrendo os grupos de botoes
	var x = 0;
	for(var i = 0; i < this.editor.config.toolbar.buttons.length; i++)
	{
		var grupo = this.editor.config.toolbar.buttons[i];

		// percorrendo os botoes do grupo e acoplando na toolbar os metodos
		for(var j = 0; j < grupo.buttons.length; j++)
		{
			
			var nomemetodo = grupo.buttons[j].value;
			var metodo = grupo.buttons[j].value;

			if(nomemetodo != '' && nomemetodo != undefined && nomemetodo != null)
			{
				try
				{
					var funcao = metodo;
					
					if(eval(funcao) != '' && eval(funcao) != undefined)
					{
						this.widgets[x++] = {
							mrp:false,
							nome:metodo+'Click',
							funcao:metodo
						};
					}
				}
				catch(e)
				{
					try
					{
						var funcao = 'MRP.Editor.Widget.'+metodo;
						
						if(eval(funcao) != '' && eval(funcao) != undefined)
						{
							this.widgets[x++] = {
								mrp: true,
								nome:metodo+'Click',
								funcao: funcao+'().init(ev)',
								funcao2: funcao+'.init(ev)',
								finish: {
									'metodo':funcao+'.finish',
									'nomemetodo':metodo
								}
							};
						}
					}
					catch(ex)
					{
						//console.log(e);	
						//console.log(ex);	
					}
				}
			} // fim if metodo
		}
	}
	
	this.editor.myEditor.widgets = this.widgets;
	
	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	this.editor.myEditor.on('editorContentLoaded',function(editor){
	
	});

	/*
	 * @autor Felipe Marques
	 * @date 04-05-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	this.editor.myEditor.on('closeWindow', function(){
		// quando clicamos 2x em uma imagem inserida no editor
		// é aberto um painel para configurar a posicao da imagens , alem de outros recursos,
		// ao fechar este painel podemos executar algo aqui
		//alert('Editor painel fechou');								
	});
	
	
	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	this.editor.myEditor.on('toolbarLoaded',function(){

		for(var i = 0; i < this.widgets.length; i++)
		{
			this.widget_atual = this.widgets[i];
			if(this.widgets[i].mrp)
			{
				var src = 'this.toolbar.on("'+this.widgets[i].nome+'", function(ev){';
					src += 'try{new '+this.widgets[i].funcao+';}';
					src += 'catch(e){try{'+this.widgets[i].funcao2+';}';
					src += 'catch(ex){alert(e);alert(ex);}}';
					src += '},this,true);';
				//console.log(src);
				eval(src);
			}
			else
			{
				var src = 'this.toolbar.on(this.widgets[i].nome,this.widgets[i].funcao,this,true);';
				//console.log(src);
				eval(src);
			}
		}

		/*
		 * @autor Felipe Marques
		 * @date 26-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		this.toolbar.on('insertimageClick',function(e){
			MRP.Editor.Widget.insertFoto.init(e);
			return false;
		});
		
		/*
		 * @autor Felipe Marques
		 * @date 26-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
        this.on('afterRender', function() {
            // Configurações para o funcionamento do code editor
			var wrapper = this.get('editor_wrapper');
            wrapper.appendChild(this.get('element'));
            this.setStyle('width', '100%');
            this.setStyle('height', '100%');
            this.setStyle('visibility', '');
            this.setStyle('top', '');
            this.setStyle('left', '');
            this.setStyle('position', '');
            this.addClass('editor-hidden');
		}, this, true);

		/*
		 * @autor Felipe Marques
		 * @date 26-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		this.on('editorKeyPress',function(e){
			MRP.Editor.LimpaTagMicrosoftWord();
		}, this, true);

		/*
		 * @autor Felipe Marques
		 * @date 26-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		this.on('editorKeyUp',function(e){
			MRP.Editor.LimpaTagMicrosoftWord();		
		}, this, true);

		/*
		 * @autor Felipe Marques
		 * @date 26-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		this.on('editorMouseDown',function(e){
		
		}, this, true);
		
		/*
		 * @autor Felipe Marques
		 * @date 26-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		this.on('editorMouseUp',function(e){
		
		}, this, true);	
		
		/*
		 * @autor Felipe Marques
		 * @date 27-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		this.on('editorClick',function(e){
			//console.log(e);
			
			var ev = e.ev;
											 
			var isRight = (ev.button) ? (ev.button == 2) : (ev.which == 3);
			if(isRight) 
			{
				alert('Botão direito do mouse bloqueado!');
				
				try
				{
					YAHOO.util.Event.stopEvent(e);	
					YAHOO.util.Event.stopEvent(ev);	
				}
				catch(e){ alert(e); }
				return false;
			}

			return true;
		
		}, this, true);	

		/*
		 * @autor Felipe Marques
		 * @date 26-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		this.on('beforeEditorClick',function(e){
											 
		});
	
	});
}

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.LimpaTagMicrosoftWord = function()
{
	// ok
	var texto = this.myEditor.get('element');
	if( texto.value.match(/\<w\:WordDocument\>/mi) )
	{
		if(!confirm('Você está copiando do Word. '+
					'\nO código proveniente do word possui formatações que podem interferir no funcionamento da página.'+
					'\nDeseja prosseguir?'))
		{
			this.myEditor.clearEditorDoc();
			texto.value = '';
		}
		else
		{
			var html = texto.value;
				// tiramos as quebras de linhas
				html = html.replace(/\n/gi,'#n#');
				// retiramos as tags meta
				html = html.replace(/((<meta(.*?)?>?)(.*?)(>))/gi,'');
				// retiramos as tags link
				html = html.replace(/((<link(.*?)?>?)(.*?)(>))/gi,'');
				// retiramos os ifs de comentarios
				html = html.replace(/((<\!\-\-\[(.*?)\]>)(.*?)(<\!\[endif\]\-\->))/gi,'');
				html = html.replace(/((<xml(.*?)>)(.*?)(<\/xml>)){0,}/gi,'');
				html = html.replace(/(class=\"(.*?)\"){0,}/gi,'');	
				html = html.replace(/(<([^>]+)>)/ig,""); 
				html = html.replace(/#n#/gi,"<br>");
				html = html.replace(/(<br><br>){2,}/gi,'');
				html = html.replace(/<br>/gi,"<br>\n");
				html = "<p>\n"+html+"\n</p>";
			
			this.myEditor.setEditorHTML( html );
			this.myEditor.saveHTML();	
		}
	}
	else
	{
		this.myEditor.saveHTML();
	}
}

/*
 * @autor Felipe Marques
 * @date 26-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Widget.addButton = function(config,grupo)
{
	// ok
	try
	{
		this.editor.toolbar.addButtonToGroup(config, grupo);
	}
	catch(e)
	{
		alert(e);
	}
}

/*
 * @autor Felipe Marques
 * @date 26-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Widget.editcode = new Object(
{
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @declare Variáveis internas
	*/
	Dom: YAHOO.util.Dom,
	Event: YAHOO.util.Event,
	Editor: MRP.Editor,
	state: 'off',
	
	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	init: function(ev)
	{
		var ta = this.Editor.myEditor.get('element');
		var iframe = this.Editor.myEditor.get('iframe').get('element');
		
		// adicionamos um evento ao textarea para que cada tecla pressionada ele grave o conteudo no editor que sera enviado via posts
		MRP.Event(ta.id,['keypress','keyup','keydown','click','blur','change'],function(){
			//console.log('digitando no code...');									
			var html = MRP.Editor.Widget.editcode.cleanHTML(this.value);
			MRP.Editor.myEditor.setEditorHTML(html);
		});
		
		if (this.state == 'on') 
		{
			this.state = 'off';
			this.Editor.myEditor.toolbar.set('disabled', false);
			
			//YAHOO.log('Show the Editor', 'info', 'example');
			//YAHOO.log('Inject the HTML from the textarea into the editor', 'info', 'example');
			this.Editor.myEditor.setEditorHTML(ta.value);
			
			if (!this.Editor.myEditor.browser.ie) 
			{
				this.Editor.myEditor._setDesignMode('on');
			}
			
			this.Dom.removeClass(iframe, 'editor-hidden');
			this.Dom.addClass(ta, 'editor-hidden');
			this.Editor.myEditor.show();
			this.Editor.myEditor._focusWindow();
		} 
		else 
		{
			this.state = 'on';
			
			//YAHOO.log('Show the Code Editor', 'info', 'example');
			this.cleanHTML(this.Editor.getHTML());
			
			//YAHOO.log('Save the Editors HTML', 'info', 'example');
			this.Dom.addClass(iframe, 'editor-hidden');
			this.Dom.removeClass(ta, 'editor-hidden');
			
			this.Editor.myEditor.toolbar.set('disabled', true);
			this.Editor.myEditor.toolbar.getButtonByValue('editcode').set('disabled', false);
			this.Editor.myEditor.toolbar.selectButton('editcode');
			this.Editor.myEditor.dompath.innerHTML = 'Editando HTML';
			this.Editor.myEditor.hide();
		}
		return false;
	},

	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	cleanHTML: function(html)
	{
		return this.Editor.myEditor.get('element').value = html;	
	}
});

/*
 * @autor Felipe Marques
 * @date 26-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Widget.clearAll = new Object(
{
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @declare Variáveis internas
	*/
	Editor: MRP.Editor,
	
	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	init: function()
	{
		if (confirm('Apagar todo o texto? Esta operação não pode ser desfeita!')) this.Editor.myEditor.clearEditorDoc();
		return false;	
	},

	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	finish: function()
	{
		
	}
});

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Widget.inserttable = new Object(
{
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * Declaração das variaveis do objeto
	*/
	
	/* 
	 * Para evitar conflito de ids do javascript no sistema, 
	 * criamos um prefix e setamos as variaveis que serao os ids dos elementos
	*/
	prefix: 'ewdg_table_',
	painel: this.prefix+'painelWidgetTabela',
	linhas: this.prefix+'linhas',
	colunas: this.prefix+'colunas',
	
	textoCabecalhoLargura: this.prefix+'textCabecalhoLargura',
	selTipoMedida: this.prefix+'selTipoMedida',
	textCabecalhoBorda: this.prefix+'textCabecalhoBorda',
	textCabecalho: this.prefix+'textCabecalho',
	textCabecalhoCorTexto: this.prefix+'textCabecalhoCorTexto',
	selCabecalhoAlinhamento: this.prefix+'selCabecalhoAlinhamento',
	textCabecalhoCorFundo: this.prefix+'textCabecalhoCorFundo',
	textCabecalhoMerge: this.prefix+'textCabecalhoMerge',
	textCabecalhoColspan:this.prefix+'textCabecalhoColspan',
	visualizacao: this.prefix+'visualizacao',

	btInserirTabela: this.prefix+'btInserirTabela',
	
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	init: function()
	{
		var html = '<div id="'+this.painel+'">';

		html += '<table width="100%" border="0">';
			
			html += '<tr>';
			html += '<td colspan="5"><b>Tamanho da Tabela</b><hr></td>';
			html += '</tr>';
			
			html += '<tr>';
			html += '<td width="13%">Linhas</td>';
			html += '<td width="50%">';
			html += '<input type="text" size="4" value="0" maxlength="3" id="'+this.linhas+'" class="digito"/>';// linhas
			html += '</td>';
			html += '<td width="11%">Colunas</td>';
			html += '<td width="16%">';
			html += '<input type="text" size="4" maxlength="3" value="0" id="'+this.colunas+'" class="digito" />';// colunas
			html += '</td>';
			html += '<td width="10%">&nbsp;</td>';
			html += '</tr>';
			
			html += '<tr>';
			html += '<td>Largura </td>';
			html += '<td>';
			html += '<input type="text" size="4" maxlength="3" value="100" id="'+this.textoCabecalhoLargura+'"/>'; // largura
			html += '<select id="'+this.selTipoMedida+'">';
				html += '<option value="porcentagem">Porcentagem</option>';
				html += '<option value="pixel">Pixel</option>';
			html += '</select>	</td>';
			html += '<td>Borda</td>';
			html += '<td>';
			html += '<input type="text" size="4" maxlength="3" value="1" id="'+this.textCabecalhoBorda+'" />'; // borda
			html += '</td>';
			html += '<td>pixel(s)</td>';
			html += '</tr>';

		html += '</table>';

		html += '<div style="width:100%; margin-top:5px; text-align:left;">';

			html += '<b>Cabeçalho da Tabela</b><hr>';		
			//html += '<div style="text-align:center">';
			//html += 'Colunas <input type="text" maxlength="3" value="0" id="borda" style="width:30px;" />'; // colunas cabecalho
			//html += '</div>';

		html += '</div>';

			html += '<table width="100%" cellpadding="0" cellspacing="1">';
				/*
				 * linha de configuracao do cabecalho
				*/			
				html += '<tr>';
					html += '<td>';
						html += 'Texto';
					html += '</td>';
					html += '<td>&nbsp;</td>';
					html += '<td align="left">';
						html += '<input type="text" maxlength="255" value="Texto" id="'+this.textCabecalho+'" width="250px;"/>';
					html += '</td>';

					html += '<td>';
						html += 'Cor Texto';
					html += '</td>';
					html += '<td>&nbsp;</td>';
					html += '<td align="left">';
						html += '<input type="hidden" id="'+this.textCabecalhoCorTexto+'" />';
						//html += '<div id="button-container2"><label for="color-picker-button2"></label></div>';
						
					html += '</td>';
				html += '</tr>';

				html += '<tr>';

					html += '<td>';
						html += 'Alinhamento';
					html += '</td>';
					html += '<td>&nbsp;</td>';
					html += '<td align="left">';
						html += '<select id="'+this.selCabecalhoAlinhamento+'">';
						html += '<option value="left">Esquerda</option>';
						html += '<option value="right">Direita</option>';
						html += '<option value="center">Centralizado</option>';
						html += '</select>';
					html += '</td>';
					
					html += '<td>';
						html += 'Cor Fundo';
					html += '</td>';
					html += '<td>&nbsp;</td>';
					html += '<td align="left">';
						html += '<input type="hidden" id="'+this.textCabecalhoCorFundo+'"/>';
						html += '<div id="button-container1"><label for="color-picker-button1"></label></div>';
					html += '</td>';

				html += '</tr>';

				html += '<tr>';
			
					html += '<td>';
						html += 'Merge';
					html += '</td>';
					html += '<td>&nbsp;</td>';
					html += '<td align="left">';
						html += '<input type="text" maxlength="2" id="'+this.textCabecalhoMerge+'" style="width:25px;"/>';
					html += '</td>';

					html += '<td>';
						html += 'Colspan';
					html += '</td>';
					html += '<td>&nbsp;</td>';
					html += '<td align="left">';
						html += '<input type="text" maxlength="2" id="'+this.textCabecalhoColspan+'" style="width:25px;"/>';
					html += '</td>';
			
				html += '</tr>';
			
			html += '</table>';

				/*
				 * linha dos botoes
				*/					
				html += '<div style="text-align:center">';
					html += '<button type="button" id="'+this.btInserirTabela+'" value="Inserir tabela">Inserir tabela</button>';
				html += '</div>';

		html += '</div>';
		
		/*
		 * preview da tabela
		*/
		html += '<div id="'+this.visualizacao+'" style="width:100%; height:220px; background:white; margin-top:10px; overflow:auto;">';
		html += '';
		html += '</div>';

		// cria o modal e seta configuracoes
		var panel = MRP.Modal.container(this.prefix+'painelInsertTable',{
			'width':'640px',
			'header':'Inserir Tabela',
			'body':html,
			'show':true
		});
		
		// aplica o focus na modal 
		panel.hideEvent.subscribe(function() 
		{
			//Just to make sure we didn't loose it
			this._setDesignMode('on');
			this._focusWindow();
		}, this, true);
		
		// inicializa o button para Inserir a Tabela no Editor
		MRP.ButtonHTML(this.btInserirTabela,'click',function(){
			alert('this.insereTabela();');	  
		});
		
		// aplica os eventos nos elementos html
		this.setEventos();
	},
	
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	setEventos: function()
	{

	},
	
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	insereTabela: function() 
	{
		var editor = MRP.Editor; 
		var linhas = parseInt(document.getElementById('linhas').value);
		var colunas = parseInt(document.getElementById('colunas').value);
		
		var visualizacao = document.getElementById('visualizacao').innerHTML;
		
		if(visualizacao == '')
		{
			var out = "<table border=1 width=100%>";
			for(var l = 0; l < linhas; l++)
			{
				out += "<tr>";
				for(var c = 0; c < colunas; c++)
				{
					out += "<td></td>";
				}
				out += "</tr>";
			}
			out += "</table>";
		}
		else
		{
			out = visualizacao;
		}
		
		win2.hide();
	}
	
});

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Widget.insertwidget = new Object(
{
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * Declaração das variaveis do objeto
	*/
	
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	init: function()
	{
		alert('insertwidget');	
	}
});

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Widget.insertfile = new Object(
{
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * Declaração das variaveis do objeto
	*/
	painel:{
		'id':'wdgPainelinsertFile',
		'dataTable':'wdgPainelinsertFile_dataTable',
		'paginacao':'wdgPainelinsertFile_paginacao',
		'modal':'wdgPainelinsertFile_modal',
		'voltar':'wdgPainelinsertFile_btVoltar',
		'principal':'wdgPainelinsertFile_principal'
	},
	html:'',
	
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	init: function()
	{
		// inicializo
		var widget = this;
		
		this.conteudo = MRP.Editor.Widget.conteudo;
		
		this.html += '<div id="'+this.painel.principal+'">';
			this.html += '<div id="'+this.painel.modal+'"></div>';
		this.html += '</div>';
		
		this.panel = MRP.Modal.container(this.painel.id,{
			'width':'470px',
			'header':'Inserindo Arquivos',
			'body':this.html,
			'show':false
		});
		
		this.panel.hideEvent.subscribe(function() 
		{
			//Just to make sure we didn't loose it
			this._setDesignMode('on');
			this._focusWindow();
		}, this, true);
		
		this.panel.show();
		
		var htmltab = '<div id="'+this.painel.dataTable+'"></div>';
			htmltab += '<div align="center" id="'+this.painel.paginacao+'"></div>';
		
		this.tabs = MRP.Tab.init(this.painel.principal,'Grupos de Arquivos',htmltab,function(tab){
			MRP.Editor.Widget.insertfile.DataTable.init(widget);			
		});
	},

	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	DataTable: new Object(
	{
		/*
		 * @autor Felipe Marques
		 * @date 12-05-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		init: function(widget,url)
		{
			MRP.DataTable.linhasPorPagina = 15;
			MRP.DataTable.container = [widget.painel.paginacao];
			MRP.DataTable.paginacao = widget.painel.dataTable;
			MRP.DataTable.config(url || MRP.Config.AJAX+'bancoArquivos/bancoArquivosLista.php',
			[
				{key:"id", label:"Num", minWidth: 60,  sortable:true},
				{key:"nm", label:"Título", minWidth: 1000, sortable:true},
				
				{key:"", minWidth: 20, formatter:"abregrupoFormat"}
			],
			[
				{key:"id", parser:"number"},
				{key:"nm", parser:"string"}
			]);
			
			// ABRIR GRUPO DE TEXTOS
			MRP.DataTable.Formatter('abregrupoFormat', function(elLiner, myDataSource, oColumn, oData){
				
				var widget = MRP.Editor.Widget.insertfile;
				var id = myDataSource.getData("id");
				var nm = myDataSource.getData("nm");
				var bt = widget.painel.id+'btFormatadorAbreGrupo'+id;
				
				elLiner.innerHTML = '<img id="'+bt+'" src="recursos/imagens/ico_folderopen.png" title="Abrir Grupo"/>';
				
				MRP.Event(bt, 'click', function(ev){
					MRP.Editor.Widget.insertfile.DataTable.abregrupoFormat(id,nm,ev);
				});	
			});
		
			MRP.DataTable.init();
		},

		/*
		 * @autor Felipe Marques
		 * @date 12-05-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		abregrupoFormat: function(conteudo,nm,ev)
		{
			var widget = MRP.Editor.Widget.insertfile;
			var	content = '<div id="testePag"></div>';
				content += '<div id="testeCont" style="text-align:center"></div>';

			MRP.Tab.addTab('Grupo '+nm,{'content':content,'href':'ewdg_abreGrupoFormat'},function(tab){
				
				MRP.DataTable.linhasPorPagina = 15;
				MRP.DataTable.container = ['testeCont'];
				MRP.DataTable.paginacao = 'testePag';
				
				MRP.DataTable.config(MRP.Config.AJAX+'bancoArquivos/bancoArquivosArquivoLista.php&qual='+conteudo,
				[
					{key:"id", label:"Num", minWidth: 60,  sortable:true},
					{key:"nm", label:"Título", minWidth: 1000, sortable:true},
					{key:"", minWidth: 20, formatter:"addContFormat"}
				],
				[
					{key:"id", parser:"number"},
					{key:"nm", parser:"string"},
					{key:"conteudo", parser:"number"}
				]);
				
				MRP.DataTable.Formatter('addContFormat', function(elLiner, myDataSource, oColumn, oData){
					var id = myDataSource.getData("id");
					var conteudo = myDataSource.getData("conteudo");
					var time = new Date().getTime();
					var bt = 'btFormatadorAbreGrupo'+id+time;
					
					elLiner.innerHTML = '<img id="'+bt+'" src="recursos/imagens/ico_add.gif" title="Adicionar arquivo."/>';
					
					MRP.Event(bt, 'click', function(ev){ 
						MRP.Editor.Widget.insertfile.setEditorHTML(conteudo,id);
					});			
				});
				
				// INICIALIZA O DATATABLE
				MRP.DataTable.init();
				
			},'ewdg_abreGrupoFormat');

		}

	}),

	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	setEditorHTML: function(conteudo,id)
	{
		var postData = 'conteudo='+conteudo+'&arquivo='+id;
		
		MRP.Ajax('POST',MRP.Config.AJAX+'bancoArquivos/bancoArquivosArquivoView.php',{
			success: function(data)
			{
				var editor = MRP.Editor;
					editor.setHTML(data.responseText);
			},
			failure: function(data)
			{
				alert(data.responseText);
			}
		},postData);
	},

	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	finish: function()
	{
		
	}
});

/*
 * @autor Felipe Marques
 * @date 12-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Widget.insertFoto = new Object( 
{
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @Declaracao das variaveis
	*/
	Dom : YAHOO.util.Dom,
	Event : YAHOO.util.Event,
	Widget: MRP.Editor.Widget,
	panel: null,
	conteudo:null,
	imagens:new Array(),
	
	/* configuração dos ids do html */
	tamanhoImg: 'ewdg_imagem_tamanhoImg',
	bordaImg: 'ewdg_imagem_bordaImg',
	margemImg: 'ewdg_imagem_margemImg',
	alinhamentoImg: 'ewdg_imagem_alinhamentoImg',
	editorImgUpload: 'ewdg_imagem_editorImgUpload',
	carregando: 'ewdg_imagem_carregando',
	listaImagens: 'ewdg_imagem_listaImagens',
	editorWidgetImgForm: 'ewdg_imagem_editorWidgetImgForm',
	
	// pasta para upload
	pastaUpload:'/arquivosUpload/',
	// guarda o html das imagens que ja foram inseridas
	html_cache: '',
	// caminho do arquivo que faz o upload da imagem
	action: '',

	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	init: function()
	{
		// ok
		// inicializo
		this.conteudo = MRP.Editor.Widget.conteudo;
		this.action =  MRP.Config.AJAX+'recursos/php/editor/widgets/imagem/imagem.php'; 
		
		var html = '<div style="margin:5px; text-align:left;">';
			html += '<b>Defini&ccedil;&otilde;es:</b> ';
			      
			html += '<select id="'+this.tamanhoImg+'" name="tamanho" size="1">';
		 	html += '<option value="80x80">80px</option>';
			html += '<option value="120x120">120px</option>';
			html += '<option value="180x180">180px</option>';
			html += '<option value="240x240">240px</option>';
			html += '<option value="480x480">480px</option>';
			html += '</select> ';
		
			html += '<select id="'+this.bordaImg+'" name="borda" size="1">';
			html += '<option value="0">Sem borda</option>';
			html += '<option value="1" selected>Com borda</option>';
			html += '</select> ';
			
			html += '<select id="'+this.margemImg+'" name="margem" size="1">';
			html += '<option value="0">Sem margem</option>';
			html += '<option value="1" selected>Com margem</option>';
			html += '</select> ';
			
			html += '<select id="'+this.alinhamentoImg+'" name="alinhamento" size="1">';
			html += '<option value="0" selected>Esquerda</option>';
			html += '<option value="1">Direita</option>';
			html += '</select>';
		
			html += '</div>';
		
			html += '<form action="'+this.action+'" enctype="multipart/form-data" method="post" name="editorWidgetImgForm" id="'+this.editorWidgetImgForm+'">';
			html += '<div style="margin:5px; text-align:left;">';
		
			html += '<b>Selecione a Imagem:&nbsp;</b>';
			html += '<input type="file" id="'+this.editorImgUpload+'" name="editorImgUpload">';		

			html += '<br>';
			html += '<div id="'+this.carregando+'" style="display:none; height:30px; margin:5px 5px 5px 5px;" align="center"><img src="'+MRP.Config.HOST+'recursos/imagens/loading.gif"></div>';
			html += '<div id="'+this.listaImagens+'" style="background:white; height:100%">Carregando Lista Imagens...</div>';
		
			html += '</div>';
			html += '</form>';
		
		//console.log(html);
		
		this.panel = MRP.Modal.container('wdgPainelinsertFoto',{
			'width':'470px',
			'header':'Inserindo imagens',
			'body':html,
			'show':true
		});
		
		// pega o que tive em cache no javascript e aplica na view das imagens
		//MRP.Get(this.listaImagens,'id').innerHTML = this.html_cache;
		this.listarImagens({
			'tamanho':'80x80',
			'conteudo':this.conteudo
		});
		
		this.panel.hideEvent.subscribe(function() 
		{
			//Just to make sure we didn't loose it
			this._setDesignMode('on');
			this._focusWindow();
		}, this, true);	

		MRP.Event(this.editorImgUpload,'change',this.upload);
	},

	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	GeraImagens: function()
	{
		// ok
		try
		{
			// pegamos todas as imagens que estao na sessao e criamos o arquivo no site
			MRP.Ajax('GET',MRP.Config.AJAX+'recursos/php/editor/widgets/imagem/geraImagens.php',
			{
				success: function(data)
				{
					if(data.responseText == '')
					{
						//alert('Sucesso!');
					}
					else
					{
						alert(data.responseText);	
					}
				}
			});
		}
		catch(e)
		{
			console.log(e);	
		}
	},

	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	listarImagens: function(options)
	{
		// ok
		if(options == undefined || options == null) options = {};
		
		var widget = this;
		var imagens = null;
		var html = '';
		var src = '';
		var listaImagens = MRP.Get(this.listaImagens,'id');
		var tamanho = options.tamanho || '80x80';
		var conteudo = options.conteudo || this.conteudo;

		/*
		 * @autor Felipe Marques
		 * @date 08-04-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		MRP.Ajax('GET',MRP.Config.AJAX+'recursos/php/editor/widgets/imagem/listaImagens.php&conteudo='+conteudo,{
			success:function(data)
			{					
				imagens = eval(data.responseText);

				if(imagens != null)
				{
					for(var i = 0; i < imagens.length; i++)
					{
						var time = new Date().getTime();

						if(imagens[i].origem == 'banco')
						{
							src = MRP.Config.HOST_PUB+imagens[i].nomeDominio+widget.pastaUpload;
							src += imagens[i].file_id;
							src += tamanho;
							src += '.';
							src += imagens[i].file_type;
							src += '?time='+time;
							src += '&tamanho='+tamanho;

							widget.imagens[i] = {
								'origem':imagens[i].origem,
								'file_id':imagens[i].file_id,
								'file_name':imagens[i].file_name,
								'file_type':imagens[i].file_type,
								'nomeDominio':imagens[i].nomeDominio,
								'tamanho':tamanho
							}

						}
						else
						{
							src = widget.action;
							src += '&mostrar=true';
							src += '&file_id='+imagens[i].file_id;
							src += '&file_name='+imagens[i].file_name;
							src += '&time='+time;
							src += '&tamanho='+tamanho;
							src += '&borda=0';
							src += '&margem=0';
							src += '&zoom=0';
							src += '&alinhamento=0';
						}
		
						html += widget.thumbView(imagens[i].file_id,imagens[i].file_name,src,i);
					}
					
					listaImagens.innerHTML = html;
				}
				else
				{
					listaImagens.innerHTML = '';	
				}
				
				widget.imagens = imagens;
			
			},
			failure:function(args)
			{
				alert(args.responseText);
			}
		});
	},
	
	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	thumbView: function(file_id,file_name,src,ponteiro)
	{
		// ok
		var html = '<span class="imgEditor">';
			html += '<a href="javascript:;" ondblclick="MRP.Editor.Widget.insertFoto.editaFoto(\''+file_id+'\',\''+file_name+'\')" title="Click duplo para editar"><img alt="'+file_name+'" title="Click duplo para editar" src="'+src+'" style="border:none"/></a>';
			html += '<a href="javascript:;" onclick="MRP.Editor.Widget.insertFoto.deleteImage(\''+file_id+'\',\''+file_name+'\');"><img style="float:left; border:none;" src="'+MRP.Config.HOST+'recursos/imagens/ico_trash.gif" title="Excluir"/></a>';
			html += '<a href="javascript:;" onclick="MRP.Editor.Widget.insertFoto.addImage(\''+file_id+'\',\''+file_name+'\','+ponteiro+');"><img style="float:right; border:none;" src="'+MRP.Config.HOST+'recursos/imagens/ico_add.gif" title="Adicionar"/></a>';
			html += '</span>';
		
		//console.log('\n'+html+'\n');
		
		return html;
	},

	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	editaFoto: function(file_id,file_name)
	{
		alert('file_id: '+file_id+' \nfile_name: '+file_name);
	},

	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	addImage : function(file_id,file_name,ponteiro)
	{
		// ok
		// pegamos o objeto do widget
		var widget = this; 
		// pegamos o objeto do editor
		var editor = MRP.Editor;
		// pegamos o tempo atual
		var time = new Date().getTime();
		
		// pego o elemento tamanho do html do form deste widget
		var tamanho = MRP.Get(this.tamanhoImg,'id').value;
		// pego o elemento borda do html do form deste widget
		var borda = MRP.Get(this.bordaImg,'id').value;
		// pego o elemento margem do html do form deste widget
		var margem = MRP.Get(this.margemImg,'id').value;
		// pego o elemento alinhamento do html do form deste widget
		var alinhamento = MRP.Get(this.alinhamentoImg,'id').value;
		// imagem		
		var imagem = widget.imagens[ponteiro];
		
		if(imagem.origem == 'banco')
		{
			// monto o src da imagem que sera inserida no editor
			var src = MRP.Config.HOST_PUB+imagem.nomeDominio+'/arquivosUpload/teste/';
				src += imagem.file_id;
				src += imagem.tamanho;
				src += '.';
				src += imagem.file_type;
				src += '?time='+time;
				src += '&tamanho='+imagem.tamanho;
		}
		else
		{
			// monto o src da imagem que sera inserida no editor
			var src = widget.action;
				src += '&mostrar=true';
				src += '&file_id='+file_id;
				src += '&file_name='+file_name;
				src += '&time='+time;
				src += '&tamanho='+tamanho;
				src += '&borda='+borda;
				src += '&margem='+margem;
				src += '&alinhamento='+alinhamento;
		}

		// monto a tag da img que sera inserida no editor
		var html = '<img ';
			html += 'rel="ewdg_imagem" ';
			html += 'src="'+src+'" ';
			html += 'title="'+file_name+' '+tamanho+'" ';
			html += 'alt="'+file_name+' '+tamanho+'" ';
		
		// configurando o estilo conforme selecionado
			html += 'style="';
		if(borda == 1)
		{
			html += 'border:1px solid black;';
		}
		
		if(margem == 1)
		{
			html += 'margin:5px 5px 5px 5px;';
		}

		if(alinhamento == 0)
		{
			html += 'text-align:left;';
		}
		else if(alinhamento == 1)
		{
			html += 'text-align:right;';
		}

			html += '" ';
		// fim da configuracao do estilo
			html += 'id="'+file_id+'"';
			html += '/>';
		
		try
		{
			this.html_cache = this.thumbView(file_id,file_name,src);		
		}
		catch(e)
		{
			alert(e);	
		}
		
		editor.setHTML(html);
		//this.panel.hide();
	},
	
	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	deleteImage: function(id,file_name)
	{
		// ok
		var widget = this;
		var editor = MRP.Editor;
		var carregando = MRP.Get(widget.carregando,'id');
		var conteudo = this.conteudo;

		// procuramos pelas imagens inseridas pelo WIDGET
		var texto = editor.getHTML();
		var er = eval('/(<img([^>]+)(id\=\"'+id+'(.*?)\"+)([ ]align\=\"(.*?)\")?>)/gi');

		if(texto.match(er))
		{
			if(confirm('Deseja excluir a imagem inserida no editor?'))
			{
				// retiramos a quebra de linha para que a ER do javascript funcione
				// pois no javascript ER nao funciona em textos de multiplas linhas
					texto.replace(/\n/gi,'#n#');
	
				// procura no texto a palavra "ewdg_imagem" e se encontrar...
				if( texto.match(/\bewdg_imagem\b/gi) )		
				{
	
					// aplica a Expressao Regular ao texto e remove a tag html da imagem do texto
					texto = texto.replace(er,'');
					// retornamos as quebras de linha
					texto = texto.replace(/#n#/gi,"\n");
	
					// limpa o Editor e aplica o texto html ja sem a imagem excluida
					editor.myEditor.clearEditorDoc();
					editor.setHTML(texto);
				}
			}
		
		} // fim if(texto.match(er))
			
		if(confirm('Deseja excluir definitivamente a imagem?'))
		{
			// mostra a imagem de carregando
			carregando.style.display = 'block';

			// fazemos uma requisicao ao arquivos Server Side do Widget para excluir a imagem da sessao
			MRP.Ajax('GET',MRP.Config.AJAX+'recursos/php/editor/widgets/imagem/excluirImagem.php&file_id='+id+'&conteudo='+conteudo+'&file_name='+file_name,{
				success:function(data)
				{
					// escondemos a imagem animada do carregando.
					carregando.style.display = 'none';
					// se houver exito na exclusao da imagem executa o metodo para dar referesh na lista de imagens
					widget.listarImagens({
						'tamanho':'80x80',
						'conteudo':widget.conteudo
					});
				},
				
				failure: function(data)
				{
					alert(data.responseText);	
				}
			});
			
		}
	},

	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	upload: function(ev)
	{
		// ok
		// verificamos se a variavel existe, essencial para o correto funcionamento
		if(MRP.Config.HOST == undefined || MRP.Config.HOST == '' || MRP.Config.HOST == null)
		{
			alert('É necessário que a variável MRP.Config.HOST esteja definida como global e esteja com o valor do endereço do host atual.');
			return false;	
		}
	
		// pegamos o proprio widget
		var widget = MRP.Editor.Widget.insertFoto;
		// pegamos o form do widget
		var formObject = MRP.Get(widget.editorWidgetImgForm,'id');
		// pegamos o objeto file
		var inputFile = MRP.Get(widget.editorImgUpload,'id');
		
		// exibimos a imagem de carregando
		var carregando = MRP.Get(widget.carregando,'id');
			carregando.style.display = 'block';
		
		// pegamos a div que vai receber a lista de imagens
		var listaImagens = MRP.Get(widget.listaImagens,'id');
		
		if(!inputFile.value.match(/(bmp|gif|png|jpeg|jpg)/gi))
		{
			carregando.style.display = 'none';
			alert('Imagem com formato inválido. \nUtilize uma das opções: .gif, .jpg, .jpeg, .png \nEnvio do arquivo cancelado!');
			return false;
		}
		else
		{
			// executamos o este metodo que ira fazer o upload atraves da lib do YAHOO no modo IFRAME
			MRP.Upload(formObject,widget.action,null,function(data){
				
				// limpamos o input file
				inputFile.value = '';
				
				// paramos o evento de Submit
				widget.Event.stopEvent(ev);
	
				// pegamos o dado de retorno da requisicao
				var data = eval(data.responseText);
				// pegamos o id do retorno
				var file_id = data[0].file_id;
				// pegamos o nome do retorno
				var file_name = data[0].file_name;
				// pegamos o tempo atual para evitar problemas com cache
				var time = new Date().getTime();
				// montamos o src da imagem
				var src = widget.action+'&mostrar=true&tamanho=80x80&file_id='+file_id+'&time='+time;
				// chamamos o metodo que lista as imagens vindas atraves de json e atribuimos ao html
				var html = widget.thumbView(file_id,file_name,src);
				
				// se a listagem de imagens nao contiver nenhuma imagem adiciona
				if(listaImagens.innerHTML == '')
				{
					listaImagens.innerHTML = html;
				}
				else
				{
					// senao concatenamos com o que ja esta na listagem de imagens
					listaImagens.innerHTML += html;
				}
				
				// ao final do processo escondemos a imagem animada do carregando.			
				carregando.style.display = 'none';
				
				try
				{
					widget.listarImagens({
						'conteudo':widget.conteudo,
						'tamanho':'80x80'
					});
				}
				catch(e)
				{
					alert(e);	
				}
	
			});
		}
	},

	/*
	 * @autor Felipe Marques
	 * @date 08-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	 *
	 * Este metodo sempre sera executado atraves do metodo MRP.SaveEditor() que ira varrer todos os widgets e ira 
	 * finalizar o funcionamento dos widgets
	*/
	finish: function()
	{
		// ok
		var texto = MRP.Editor.getHTML();
		
		// verifico se existe alguma imagem do widget e acionamos o metodo que vai criar a imagem 
		// na pasta do arquivosUpload da raiz do site
		if( texto.match(/rel\=\"ewdg\_imagem\"/gi) )
		{
			try
			{
				this.GeraImagens();
			}
			catch(e)
			{
				console.log(e);	
			}
		}	
	}
});

/*
 * @autor Felipe Marques
 * @date 09-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.FinalizaWidgets = function(callback)
{
	// ok
	var widgets = this.myEditor.widgets;
	
	for(var i = 0; i < widgets.length; i++)
	{
		try
		{
			// nome do metodo do widget
			var funcao = eval(widgets[i].finish.metodo);
			// chama o metodo do widget e corrige o escopo da funcao para o proprio Widget
				funcao.call(eval('MRP.Editor.Widget.'+widgets[i].finish.nomemetodo));
		}
		catch(e)
		{
			//console.log(widgets[i].funcao3);
			//console.log(e);	
		}
	}
	
	callback?callback():null
}

/*
 * @autor Felipe Marques
 * @date 09-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.SaveEditor = function()
{
	// este método é executado automaticamente toda vez que a funcao MRP.Submit é acionada
	// utilizamos de callback para evitar que o editor seja salvo antes do FinalizaWidgets terminar
	this.FinalizaWidgets(function(){
		MRP.Editor.myEditor.saveHTML();	
	});
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.setHTML = function(str)
{
	return this.myEditor.execCommand('inserthtml',str);	
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.getHTML = function(str)
{
	return this.myEditor.getEditorHTML();
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.setConfig = function(config)
{
	this.config = config;
}

/*
 * @autor Felipe Marques
 * @date 08-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Simples = function(id,opcoes)
{
	// ok
	try 
	{ 
		this.myEditor.destroy(); 
		this.myEditor = null;
		this.config = null;
	}
	catch(e){}

	if(id == '' || id == undefined)
	{
		alert('ID do editor indefinido.');	
		return false;
	}
	
	var Dom = YAHOO.util.Dom;
	var	Event = YAHOO.util.Event;

	if(opcoes != '' && opcoes != null && opcoes != undefined && typeof(opcoes) == 'object')
	{
		this.setConfig(opcoes);
	}

	if(this.config == '' || this.config == null || this.config.length <= 0)
	{
		this.config = {
			height: '300px',
			width: '665px',
			animate: true,
			dompath: true,
			focusAtStart: true,
			toolbar: {
				titlebar: 'Texto',
				buttons:[ ]
			}
		};
	}

	//this.setFontFamilySize();
	this.setFontType();
	this.setFontSyle();
	//this.setTextStyle();
  	this.setAlignment();
	this.setIndentList();
	this.setControlFormat();
	//this.setInsertItem();

	this.myEditor = new YAHOO.widget.Editor(id, this.config);
	this.myEditor.render();
}

/*
 * @autor Felipe Marques
 * @date 09-04-2010
 *
 * @method
 * @access 
 * @params 
 * @return 
*/
MRP.Editor.Completo = function(id,opcoes)
{
	// ok
	try 
	{ 
		this.myEditor.destroy(); 
		this.myEditor = null;
		this.config = null;
	}
	catch(e){}

	if(id == '' || id == undefined)
	{
		alert('ID do editor indefinido.');	
		return false;
	}

	var Dom = YAHOO.util.Dom;
	var	Event = YAHOO.util.Event;

	if(opcoes != '' && opcoes != null && opcoes != undefined && typeof(opcoes) == 'object')
	{
		this.setConfig(opcoes.config);
		if(opcoes.config.grupos != undefined && opcoes.config.grupos.length > 0)
		{
			this.Toolbar.setGrupo(opcoes.config.grupos);
		}
		else
		{
			this.Toolbar.setAll();
		}
	}

	if(this.config == '' || this.config == null || this.config.length <= 0)
	{
		this.config = {
			height: '300px',
			width: '665px',
			animate: true,
			dompath: true,
			focusAtStart: true,
			toolbar: {
				titlebar: 'Texto',
				buttons:[ ]
			}
		};
		this.Toolbar.setAll();
	}

	this.myEditor = new YAHOO.widget.Editor(id, this.config);
	this.Toolbar.on();
	this.myEditor.render();
	
	return this.myEditor;
}
/*
 * @autor Felipe Marques
 * @date 21-01-2010
 *
 * @namespace MODULO
 * @desc class e namespace utilizado genericamente para todos os modulos.
*/
var MODULO = {};
MODULO.registraMetodo = function(nome_metodo,metodo)
{
	var estrutura = '';
		estrutura += 'MODULO.'+nome_metodo+' = '+metodo;
	
	eval(estrutura);
}
