/*
 * @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 = {};

/*
 * Objeto que auxilia na publicacao
*/
MRP.Publica = {};

/*
 * @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.Efeito = new Object({

	init: function()
	{
		
	},
	
	focus: function(obj)
	{
		// inicializa
		this.init();
		
		// tenta acessar a propriedade id do objeto se nao tenta pegar o objeto
		try{ obj.id; }catch(e){ var id = MRP.Get(obj,'id'); }
		
		// faz o focus
		obj.focus();
		
		// coloca um fundo amarelo
		obj.style.backgroundColor = 'yellow';
		
		// tira o background apos um evento
		MRP.Event(obj.id,['click','blur','focus','keypress','keyup','keydown'],function(){
			setTimeout(function(){
				obj.style.backgroundColor = 'white';																			  
			},obj.timer || 3000);
		});
				
	}
	
});

/*
 * @autor Felipe Marques
 * @date 22-04-2010
 *
 * @method Event
 * @access public
 * @params variable
 * @return boolean
*/
MRP.Chart = new Object({

});

/*
 * @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',
				'charts'
				
			], 
			base: 'recursos/yui/build/',
			loadOptional: false,
			onSuccess: function() 
			{
				if(callback != '' && callback != undefined && callback != null)
				{
					callback();
				}
				else
				{
					try
					{
						MODULO.Carregar();
					}
					catch(e)
					{
						alert(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
	*/
	javascript: function(arrUrls,callback)
	{
		//ok
		YAHOO.util.Get.script(arrUrls, { 
			onSuccess: function() {
				callback?callback():null
			},
			onFailure: function(){
				alert('Erro ao carregar o(s) arquivo(s)!\nURL: '+arrUrls.toString());
			}
		});
	}
});

/*
 * @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.call(MRP,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)
	{
		try
		{

			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;
				}
			}
		}
		catch(e)
		{
			//console.log(e);	
		}
		
	}
});

/*
 * @autor Felipe Marques
 * @date 18-01-2010
 *
 * @method 
 * @access 
 * @params 
 * @return 
*/
MRP.Modal = new Object({
	// ok
	/*
	 * @autor Felipe Marques
	 * @date 18-01-2010
	 *
	 * @method 
	 * @access 
	 * @params 
	 * @return 
	*/
	container: function(id,opcoes, callback)
	{
		// ok
		
		try
		{
			
			try{ win.destroy(); YAHOO.example.dialog1.destroy(); }catch(e){}
			
			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 18-01-2010
	 *
	 * @method 
	 * @access 
	 * @params 
	 * @return 
	*/
	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();
	
		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)
{
	// ok
	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)
{
	// ok
	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,opcoes)
{
	// ok
	var btCriarNovo = new YAHOO.widget.Button(id_html,opcoes || null);
	
	if(callback == '' || typeof(callback) == "undefined")
	{
		callback = function(){}	
	}
	
	if(evento != '')
	{
		YAHOO.util.Event.on(id_html, evento, callback);
	}
	
	return btCriarNovo;
}

/*
 * @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
	// 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)
{
	// ok
	// 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
	// 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: 'Tamanho'/*'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, 18 ], 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: 'Html Tag <p>', 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 Imagem', value: 'insertFoto' },/*{ type: 'push', label: 'Inserir Imagem2', value: 'insertimage' },*/
				/*{ 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.setFontType();
	this.setFontFamilySize();
	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){
		MRP.Editor.VerificaConteudoWidget();		
	});

	/*
	 * @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 
 	 *
	 * Este metodo tem por objetivo modificar a tela de insercao de link
	 *
	 * !!!!!!!!!!!!!!NAO APAGAR!!!!!!!!!!!!NAO APAGAR!!!!!!!!
	*/
	/*
	var oEditor = this.editor.myEditor;
	oEditor._handleCreateLinkClick = function() {
		oEditor.on('afterExecCommand', function() {
			var str = prompt('URL: ', 'link');
			var el = this.currentElement[0].setAttribute('href', str);
		}, oEditor, this);
	};
	*/

	/*
	 * @autor Felipe Marques
	 * @date 26-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
 	 *
	 * Este metodo tem por objetivo modificar a tela de insercao de imagem
	 *
	 * !!!!!!!!!!!!!!NAO APAGAR!!!!!!!!!!!!NAO APAGAR!!!!!!!!
	*/
	/*
	var oEditor = this.editor.myEditor;
	oEditor._handleInsertImageClick = function() {
		oEditor.on('afterExecCommand', function() {
			//var str = prompt('URL: ', 'link');
			//var el = this.currentElement[0].setAttribute('href', str);
		}, oEditor, this);
	};
	*/
	
	/*
	 * @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){
			//console.log(e);													
		});
		
		/*
		 * @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('Para copiar utilize Ctrl + C, e para colar Ctrl + V');
				
				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){
											 
		});
	
	});
}

MRP.Editor.VerificaConteudoWidget = function()
{
	var msgpost = this.getHTML().replace(/\n/gi,'#n#');
	var imagens_editor = msgpost.match(/(<img([^>]+))/gi);
	
	if(imagens_editor.length > 0)
	{
		for(var i = 0; i < imagens_editor.length; i++)
		{
			///////////////////////////////////////
			// Verificando os caminhos relativos //
			///////////////////////////////////////
			
			if(imagens_editor[i].match(/\.\.\//gi))
			{
				if(confirm('Existem links ou imagens neste texto que estão com o endereço relativo, '+
						   'podendo gerar erros. \nDeseja que o sistema tente arrumar o problema?'))
				{
					msgpost = msgpost.replace(/\.\.\//gi,'http://');
				}
			}
			
			/////////////////////////////////////////////
			// Verificando se há widget YOUTUBE antigo //
			/////////////////////////////////////////////
			
			if(imagens_editor[i].match(/title\=\"YOUTUBEWIDGET\=(.*?)\"/gi))
			{
				if(confirm('Existem vídeos do youtube no formato antigo.\nDeseja atualizar?'))
				{
					var videoURL = imagens_editor[i].match(/(YOUTUBEWIDGET\=)(.*?)(\")/gi)[0].replace(/YOUTUBEWIDGET\=/gi,"").replace(/\"/gi,"");
					var videoID = videoURL.split('/').pop();
					var videoWidth = imagens_editor[i].match(/width\=\"[0-9]{0,}\"/gi)[0].replace(/width\=/gi,"").replace(/\"/gi,"");
					var videoHeight = imagens_editor[i].match(/height\=\"[0-9]{0,}\"/gi)[0].replace(/height\=/gi,"").replace(/\"/gi,"");
					var thumb = '<img class="yui-img" rel="ewdg_videos_youtube" id="'+videoID+'" src="http://img.youtube.com/vi/'+videoID+'/0.jpg" width="'+videoWidth+'" height="'+videoHeight+'">';
					
					msgpost = msgpost.replace(imagens_editor[i]+'>',thumb);
				}
			}
		}
		
		msgpost = msgpost.replace(/#n#/gi,"\n");
		this.myEditor.clearEditorDoc();
		this.myEditor.setEditorHTML( msgpost );
		this.myEditor.saveHTML();	
	}
}

/*
 * @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,['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
	*/
	prefix: 'ewdg_widget_',
	seleciona_widget: this.prefix+'seleciona_widget',
	panel: null,
	
	/*
	 * @autor Felipe Marques
	 * @date 27-04-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	init: function()
	{
		// ok
		var html;
		
		html = '<select id="'+this.seleciona_widget+'" style="width:90px;">';
			html += '<option value="">Selecione</option>';
			html += '<option value="mapas">Mapas</option>';
			html += '<option value="videos">Vídeos</option>';
		html += '</select>';
		
		// cria o modal e seta configuracoes
		this.panel = MRP.Modal.container(this.prefix+'painelInsertWidget',{
			'width':'160px',
			'header':'Grupo de Aplicativos',
			'body':html,
			'show':true
		});
		
		// aplica o focus na modal 
		this.panel.hideEvent.subscribe(function() 
		{
			//Just to make sure we didn't loose it
			this._setDesignMode('on');
			this._focusWindow();
		}, this, true);
		
		// aplica o evento onchange para o combo de escolha do tipo de widget
		MRP.Event(this.seleciona_widget,'change',function(ev){
			if(this.value != '') MRP.Editor.Widget.insertwidget.initGrupo(this.value);											  
		});
	},
	
	/*
	 * @autor Felipe Marques
	 * @date 31-05-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	initGrupo: function(grupo)
	{
		// ok
		// fecha o painel principal
		this.panel.hide();

		// escolhe qual o grupo de widgets que ira trabalhar
		switch(grupo)
		{
			case 'mapas':
				this.Mapas.init(this);
			break;
			
			case 'videos':
				this.Videos.init(this);
			break;
		}
	},
	
	/*
	 * @autor Felipe Marques
	 * @date 31-05-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	Mapas: new Object({

		/*
		 * @autor Felipe Marques
		 * @date 31-05-2010
		 *
		 * Declaração das variaveis do objeto
		*/
		widget: null,

		/*
		 * @autor Felipe Marques
		 * @date 31-05-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		init: function(widget)
		{
			this.widget = widget;

			var html;
			
			html = '<select id="" style="width:90px;">';
				html += '<option value="google">Google</option>';
				html += '<option value="google">Microsoft Earth</option>';
				html += '<option value="google">Outros</option>';
			html += '</select>';

			// cria o modal e seta configuracoes
			this.panel = MRP.Modal.container(this.prefix+'painelInsertWidget',{
				'width':'170px',
				'header':'Aplicativos para Mapas',
				'body':html,
				'show':true
			});
			
			// aplica o focus na modal 
			this.panel.hideEvent.subscribe(function() 
			{
				//Just to make sure we didn't loose it
				this._setDesignMode('on');
				this._focusWindow();
			}, this, true);
			
			// fechamos a modal atual
			this.panel.hide(); 
			
			// como ainda nao ha outro servico de Mapa a ser incluido startamos o Google Maps
			this.Google.init();

		},

		/*
		 * @autor Felipe Marques
		 * @date 31-05-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		Google: new Object({

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * Declaração das variaveis do objeto
			*/
			objMapa: null,
			map: null,
			marker: null,
			zoom: 15,
			latitude: -49.2529178,
			longitude: -25.4506578,
			panel: null,
			geocoder: null,
			objInputPesquisarEndereco: null,
			objBtPesquisarEndereco: null,
			url_imagem_mapa: null,
			GoogleMapsLargura:null,
			GoogleMapsAltura:null,
			GoogleMapsZoom:null,
	
			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			init: function()
			{
				// referencia ao objeto atual, Google
				var _this = this;
				var html = '';
				
				html += '<div>';

						html += '<div id="PainelPesquisa" style="float:left; margin: 5px; background-color:none; z-index:1000 !important;">';
							html += '<div>Endereço:</div>';
							html += '<div>';
								html += '<textarea id="inputPesquisarEndereco" style="width: 400px !important; font-size:14px; padding:3px;"></textarea>';
								html += '<br><button type="button" id="btPesquisarEndereco" name="btPesquisarEndereco" value="Pesquisar">Pesquisar</button>';
							html += '</div>';
						html += '</div>';

						html += '<div id="PainelOpcoes" style="margin: 5px; background-color:none; z-index:1000 !important;">';
							html += '<table style="margin-top:10px;">';
								html += '<tr>';
									html += '<td>Largura: </td>';
									html += '<td><input type="text" id="GoogleMapsLargura" value="630" style="width: 30px; font-size:10px; padding:3px;"/> px</td>';
								html += '</tr>';
								html += '<tr>';
									html += '<td>Altura: </td>';
									html += '<td><input type="text" id="GoogleMapsAltura" value="400" style="width: 30px; font-size:10px; padding:3px;"/> px</td>';
								html += '</tr>';
								html += '<tr>';
									html += '<td>Zoom: </td>';
									html += '<td><input type="text" id="GoogleMapsZoom" value="15" style="width: 30px; font-size:10px; padding:3px;"/></td>';
								html += '</tr>';
							html += '</table>';
						html += '</div>';
						
				html += '</div>';

				html += '<div id="mapGoogleMaps" style="width:100%; height:400px; clear:both;">';
					html += '<div style="text-align:center">';
					html += '<img src="recursos/imagens/loading.gif"/>';
					html += '<br>Carregando Google Maps...';
					html += '</div>';
				html += '</div>';

				// cria o modal e seta configuracoes
				this.panel = MRP.Modal.container(this.prefix+'painelInsertWidgetGoogleMaps',{
					'width':'640px',
					'header':'Google Maps',
					'body':html,
					'show':true
				});
				
				// aplica o focus na modal 
				this.panel.hideEvent.subscribe(function() 
				{
					//Just to make sure we didn't loose it
					this._setDesignMode('on');
					this._focusWindow();
				}, this.panel, true);
				
				this.panel.beforeHideEvent.subscribe(function(){
					// para liberar o uso de memoria do google maps ao fechar a modal o google maps é descarregado
					try{ GUnload(); }catch(e){ alert(e); }
				});

				// bloqueia a pesquisa até que o mapa esteja totalmente carregado
				this.objInputPesquisarEndereco = MRP.Get('inputPesquisarEndereco','id');
				this.objInputPesquisarEndereco.style.backgroundColor = 'yellow';
				this.objInputPesquisarEndereco.onfocus = function(e){ this.style.backgroundColor = 'yellow'; };
				this.objInputPesquisarEndereco.onblur = function(e){ this.style.backgroundColor = 'white'; };
				this.objInputPesquisarEndereco.onkeypress = function(e){ if(e.keyCode == 13) _this.PesquisarEndereco(_this.objInputPesquisarEndereco.value); }

				// cria o botao que pesquisa o endereco
				this.objBtPesquisarEndereco = MRP.ButtonHTML('btPesquisarEndereco','click',function(ev){
					_this.PesquisarEndereco(_this.objInputPesquisarEndereco.value);								   
				},{disabled:true});	

				// botoes de opcoes do mapa
				this.mapGoogleMaps = MRP.Get('mapGoogleMaps','id');
				this.GoogleMapsLargura = MRP.Get('GoogleMapsLargura','id');
				this.GoogleMapsAltura = MRP.Get('GoogleMapsAltura','id');
				this.GoogleMapsZoom = MRP.Get('GoogleMapsZoom','id');
	
				MRP.Event(this.GoogleMapsLargura.id,['keypress','keyup','keydown'],function(e){
					var zoom = _this.GoogleMapsZoom.value;
					var tamanho = _this.GoogleMapsLargura.value+'x'+_this.GoogleMapsAltura.value;
					
					_this.mapGoogleMaps.style.width = this.value+'px';
					_this.CriaUrlMapaEstatico(_this.latitude,_this.longitude,zoom,tamanho)																				
				});

				MRP.Event(this.GoogleMapsAltura.id,['keypress','keyup','keydown'],function(e){
					var zoom = _this.GoogleMapsZoom.value;
					var tamanho = _this.GoogleMapsLargura.value+'x'+_this.GoogleMapsAltura.value;
					
					_this.mapGoogleMaps.style.height = this.value+'px';
					_this.CriaUrlMapaEstatico(_this.latitude,_this.longitude,zoom,tamanho)																				
				});

				MRP.Event(this.GoogleMapsZoom.id,['keypress','keyup','keydown'],function(e){
					
					var zoom = parseInt(this.value);
					
					if(zoom >= 0 && zoom <= 19)
					{
						var tamanho = _this.GoogleMapsLargura.value+'x'+_this.GoogleMapsAltura.value;

						_this.setZoom(zoom);
						_this.CriaUrlMapaEstatico(_this.latitude,_this.longitude,zoom,tamanho)																				
					}
					else if(zoom < 0 || zoom > 19)
					{
						alert('O zoom deve estar entre 0 e 19');	
					}
				});

				// carrega a biblioteca do google maps diretamente da fonte online
				MRP.Loader.javascript(['http://www.google.com/jsapi'],function(){
					google.load("maps", "2", {
						callback: function(){
							// chama o metodo que inicia o mapa apos o carregamento da biblioteca
							// ajusta o escopo da chamada para o objeto Google dentro do widget
							_this.initMapa.call(_this);
						}
					});
				});

			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			initMapa: function()
			{
				/*
				 * Inicializando as variáveis
				*/
				var _this = this;
				this.objMapa = document.getElementById("mapGoogleMaps");

				try
				{
					this.map = new GMap2(this.objMapa);
					this.map.setCenter(new GLatLng(this.longitude,this.latitude), this.zoom);
					this.map.setUIToDefault();
	
					this.CriaMarcador('<div style="margin:5px;"><img align="left" src="recursos/imagens/logomarca_pucpr.gif"/>Pontifícia Universidade Católica do Paraná - Curitiba<br>Rua Imaculada Conceição 1155 - Prado Velho <br>CEP: 80215-901 - Curitiba - Paraná</div><div><button type="button" id="btAdicionarMapa" value="Adicionar Mapa">Adicionar Mapa</button></div>',this.latitude,this.longitude,true);
					this.geocoder = new GClientGeocoder();

					// habilita o inptu do endereco e da um focus nesse campo
					this.objInputPesquisarEndereco.focus();
					
					// habilita o botao pesquisar
					this.objBtPesquisarEndereco.set('disabled',false);

					setTimeout(function(){
						
						MRP.ButtonHTML('btAdicionarMapa','click',function(ev){
							_this.AdicionaMapaNoEditor();
						});
					
					},2000);

				}
				catch(e)
				{
					alert(e);	
				}
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			Loading: function(ligado,msg)
			{
				if(ligado)
				{
					this.loading = document.createElement('div');
					this.loading.id = 'carregando'+(new Date().getTime());
					this.loading.style.position = 'absolute';
					this.loading.style.zIndex = 1000;
					this.loading.style.backgroundColor = 'red';
					this.loading.style.color = 'white';
					this.loading.style.fontWeight = 'bold';
					this.loading.style.top = 0;
					this.loading.style.left = 0;
					this.loading.innerHTML = msg || 'Carregando...';

					this.objMapa.appendChild(this.loading);
				}
				else if(!ligado)
				{
					this.loading.style.display = 'none';	
				}
			},
			
			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			PesquisarEndereco: function(endereco /*string*/)
			{
				var _this = this;
				var geocoder = this.geocoder;
				var map = this.map;
				
				this.Loading(true);
				
				if (geocoder) 
				{
					geocoder.getLatLng(endereco,function(point){
						
						if (!point) 
						{
							_this.CriaMarcador('Endereço não encontrado!',_this.latitude,_this.longitude,true);
							_this.Loading(false);
						} 
						else
						{
							geocoder.getLocations(endereco, function(response){
								if (!response || response.Status.code != 200)
								{
									var latitude = _this.latitude;
									var longitude = _this.longitude;
									_this.CriaMarcador('Não foi possível encontrar o endereço <b>'+endereco+'</b>',latitude,longitude,true);
									_this.Loading(false);
								}
								else
								{
									var place = response.Placemark[0];
									var latitude = place.Point.coordinates[0];
									var longitude = place.Point.coordinates[1];
									var html = '';
									
									var endereco_completo = place.address;
									var nomepais = '', siglapais = '', estado = '', cidade = '', bairro = '', cep = '', endereco = '';
									
									try{ nomepais = place.AddressDetails.Country.CountryName }catch(e){}
									try{ siglapais = place.AddressDetails.Country.CountryNameCode }catch(e){}
									try{ estado = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName }catch(e){}
									try{ cidade = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName }catch(e){}
									try{ bairro = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.DependentLocalityName }catch(e){}
									try{ cep = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber }catch(e){}
									try{ endereco = place.AddressDetails.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName }catch(e){}
									
									html += '<div style="margin:10px; width:300px;">';
									
									if(endereco != '')
										html += '<div><b>Endereço</b>: '+endereco+'</div>';
									if(bairro != '')
										html += '<div><b>Bairro</b>: '+bairro+'</div>'; 
									if(cidade != '')	
										html += '<div><b>Cidade</b>: '+cidade+'</div>'; 
									if(cep != '')	
										html += '<div><b>CEP</b>: '+cep+'</div>';
									if(estado != '')	
										html += '<div><b>Estado</b>: '+estado+'</div>';
									if(nomepais != '')	
										html += '<div><b>País</b>: '+nomepais+'</div>';
										
										html += '<div>';
										html += '<button type="button" id="btAdicionarMapa" value="Adicionar Mapa">Adicionar Mapa</button>';
										html += '</div>';
									html += '</div>';
									
									_this.latitude = latitude;
									_this.longitude = longitude;
									_this.CriaUrlMapaEstatico(latitude,longitude,_this.zoom);
									_this.CriaMarcador(html,latitude,longitude,true);

									MRP.ButtonHTML('btAdicionarMapa','click',function(ev){
										_this.AdicionaMapaNoEditor();
									});

									_this.Loading(false);
								}										 
							});
						}
					});
				}
				else
				{
					_this.Loading(false);
				}
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			AdicionaMapaNoEditor: function(e)
			{
				var _this = this;
				var altura = MRP.Get('GoogleMapsAltura','id');
				var largura = MRP.Get('GoogleMapsLargura','id');
				var zoom = MRP.Get('GoogleMapsZoom','id');
				var tamanho = largura.value+'x'+altura.value;

				if(altura.value == '' || altura.value > 600)
				{
					MRP.Efeito.focus(altura);
					
					if(altura.value > 600)
					{
						alert('A altura não pode ultrapassar 600px');
					}
					else
					{
						alert('Preencha o campo altura!');
					}
				}
				else if(largura.value == '' || largura.value > 800)
				{
					MRP.Efeito.focus(largura);
					
					if(largura.value > 800)
					{
						alert('A largura não pode ultrapassar 800px!');
					}
					else
					{
						alert('Preencha o campo largura!');	
					}
				}
				else if(zoom.value == '' || (zoom.value > 19 || zoom.value < 0))
				{
					MRP.Efeito.focus(zoom);	
					
					if(zoom.value > 19 || zoom.value < 0)
					{
						alert('O zoom deve estar entre 0 e 19!');
					}
					else
					{
						alert('Preencha o campo zoom !');
					}
				}
				else
				{
					_this.CriaUrlMapaEstatico(_this.latitude,_this.longitude,zoom.value,tamanho)
					_this.panel.hide();
					MRP.Editor.setHTML('<img rel="ewdgGoogleMaps" src="'+_this.url_imagem_mapa+'"/>');
				}
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			setZoom: function(zoom)
			{
				this.map.setCenter(this.map.getCenter(),zoom);
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			getZoom: function()
			{
				return this.map.getZoom();
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			CriaUrlMapaEstatico: function(latitude,longitude,zoom,tamanho)
			{
				this.url_imagem_mapa = 'http://maps.google.com/staticmap?'
										+ 'center='+longitude+','+latitude+'&' // latitude e longitude
										+ 'size='+(tamanho || '450x450')+'&'
										+ 'maptype=mobile&'
										+ 'markers='+longitude+','+latitude+'&'
										+ 'zoom='+zoom+'&';
										+ 'sensor=true_or_false';
										
				return this.url_imagem_mapa;
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			CriaMarcador: function(html,latitude,longitude,mapcenter)
			{
				var _this = this;
				
				if(mapcenter) this.map.setCenter(new GLatLng(longitude,latitude),this.zoom);
				
				var marker = new GMarker(new GLatLng(longitude,latitude));
				this.map.addOverlay(marker);
				marker.openInfoWindowHtml(html);

				GEvent.addListener(marker, "click", function() {
				   marker.openInfoWindowHtml(html);

					MRP.ButtonHTML('btAdicionarMapa','click',function(ev){
						_this.AdicionaMapaNoEditor();
					});
				});
			}
			
		})
	}),

	/*
	 * @autor Felipe Marques
	 * @date 31-05-2010
	 *
	 * @method
	 * @access 
	 * @params 
	 * @return 
	*/
	Videos: new Object({

		/*
		 * @autor Felipe Marques
		 * @date 31-05-2010
		 *
		 * Declaração das variaveis do objeto
		*/
		widget:null,

		/*
		 * @autor Felipe Marques
		 * @date 31-05-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		init: function(widget)
		{
			var html;
			
			html = '<select id="" style="width:90px;">';
				html += '<option value="youtube">Youtube</option>';
				html += '<option value="vimeo">Vímeo</option>';
				html += '<option value="uol">Uol</option>';
			html += '</select>';

			// cria o modal e seta configuracoes
			this.panel = MRP.Modal.container(this.prefix+'painelInsertWidgetVideos',{
				'width':'170px',
				'header':'Serviço de Vídeo',
				'body':html,
				'show':true
			});
			
			// aplica o focus na modal 
			this.panel.hideEvent.subscribe(function() 
			{
				//Just to make sure we didn't loose it
				this._setDesignMode('on');
				this._focusWindow();
			}, this, true);
			
			// fecha o painel atual
			this.panel.hide();
			
			// como não será implantado outro servico de video alem do youtube neste momento chamamos o padrao.
			this.Youtube.init();
		},
		
		/*
		 * @autor Felipe Marques
		 * @date 31-05-2010
		 *
		 * @method
		 * @access 
		 * @params 
		 * @return 
		*/
		Youtube: new Object({
			
			/*
			 * Declaração de variaveis
			*/
			prefix:'ewdg_youtube',
			enderecoVideo: null,
			larguraVideo: 520,
			alturaVideo: 400,
			
			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			init:function()
			{
				this.enderecoVideo = [
					'http://www.youtube.com/watch?v=tI8DDzfFOts', // desenho industrial
					'http://www.youtube.com/watch?v=WgwDJxQ50nA', // educacao fisica
					'http://www.youtube.com/watch?v=We02O9cUCfY', // direito
					'http://www.youtube.com/watch?v=hzKF7mFOs3A', // administracao
					'http://www.youtube.com/watch?v=TtinJ-Y0UZQ' // psicologia
				];
				
				var _this = this;				
				
				var html =
					'<table>'+
						'<tr>'+
							'<td><b>Endereço</b></td>'+
							'<td><b>Largura</b></td>'+
							'<td>&nbsp;</td>'+
							'<td><b>Altura</b></td>'+
							'<td>&nbsp;</td>'+
						'</tr>'+
						'<tr>'+
							'<td><input id="enderecoYoutube" type="text" style="width:350px;" value="http://"/></td>'+
							'<td><input id="larguraYoutube" type="text" style="width:50px;" maxlength="4" value="'+this.larguraVideo+'"/></td>'+
							'<td> x </td>'+
							'<td><input id="alturaYoutube" type="text" style="width:50px;" maxlength="4" value="'+this.alturaVideo+'"/></td>'+
							'<td><button name="btEwdgVideosYoutube" id="btEwdgVideosYoutube" value="Ok">Ok</button></td>'+
						'</tr>'+
						'<tr>'+
							'<td colspan="5" align="center"><div id="loadingPlayer" style="text-align:center;"><img src="recursos/imagens/loading.gif"/> <br>Carregando vídeo...</div></td>'+
						'</tr>'+
						'<tr>'+
							'<td colspan="5" align="center"><div id="ytapiplayer"></div></td>'+
						'</tr>'+
					'</table>'+
					'<div align="right">'+
						'<button name="btEwdgVideosAddEditor" id="btEwdgVideosAddEditor" value="Adicionar Vídeo">Adicionar Vídeo</button>'+
					'</div>';


				// cria o modal e seta configuracoes
				this.panel = MRP.Modal.container(this.prefix+'painelInsertWidgetVideosYoutube',{
					'width':'550px',
					'header':'Youtube',
					'body':html,
					'show':true
				});
							
				// aplica o focus na modal 
				this.panel.hideEvent.subscribe(function() 
				{
					//Just to make sure we didn't loose it
					this._setDesignMode('on');
					this._focusWindow();
				}, this, true);
				
				this.panel.beforeHideEvent.subscribe(function(){
					// para liberar o uso de memoria do google maps ao fechar a modal o google maps é descarregado
					try
					{ 
						ytplayer.setVolume(0);
						ytplayer.mute();
						ytplayer.pauseVideo();
						ytplayer.seekTo(0, true);
						ytplayer.stopVideo();
						ytplayer.clearVideo();
						ytplayer.innerHTML = '';
					}catch(e){ alert(e); }
				});
				
				MRP.ButtonHTML('btEwdgVideosYoutube','click',function(e){
					var endereco = MRP.Get('enderecoYoutube','id');												  
					var largura = MRP.Get('larguraYoutube','id');
					var altura = MRP.Get('alturaYoutube','id');
					
					if(endereco.value == '' || endereco.value == 'http://')
					{
						MRP.Efeito.focus(endereco);
						if(!MRP.isUrl(endereco.value))
						{
							alert('Preencha o endereço do vídeo com uma URL válida!');
						}
						else
						{
							alert('Preencha o endereço do vídeo!');
						}
						return false;
					}
					else if(largura.value == '' || largura.value < 0)
					{
						MRP.Efeito.focus(largura);
						alert('Largura do vídeo inválida!');
						return false;
					}
					else if(altura.value == '' || altura.value < 0)
					{
						MRP.Efeito.focus(altura);
						alert('Altura do vídeo inválida!');
						return false;
					}
					else
					{
						_this.enderecoVideo = endereco.value;
						_this.larguraVideo = largura.value;
						_this.alturaVideo = altura.value;
						
						_this.trocaVideo(_this.enderecoVideo.split("=")[1],_this.larguraVideo,_this.alturaVideo);
					}
					
				});
				
				MRP.ButtonHTML('btEwdgVideosAddEditor','click',function(){
					var videoID = MRP.Get('enderecoYoutube','id').value.split("=")[1];
																		
					MRP.Editor.setHTML('<img rel="ewdg_videos_youtube" id="'+videoID+'" src="'+_this.getThumb(videoID)+'" width="'+_this.larguraVideo+'" height="'+_this.alturaVideo+'"/>');
					_this.panel.hide();
				});

				// carrega a biblioteca do google youtube diretamente da fonte online
				MRP.Loader.javascript(['http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js'],function(){
					var videoID = Math.floor(Math.random()*5); // random entre 0 e 4
					MRP.Get('enderecoYoutube','id').value = _this.enderecoVideo[videoID];
					_this.embedPlayer(_this.enderecoVideo[videoID].split("=")[1],_this.larguraVideo,_this.alturaVideo);	
				});

			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			getThumb: function(videoID,posicao)
			{
				if(posicao == undefined || posicao == '') posicao = 1;
				if(posicao > 4)
				{
					alert('Thumbnail não encontrado!');
					return false;
				}
				
				/*
				http://i3.ytimg.com/vi/VIDEO_ID/default.jpg - Small
				http://i3.ytimg.com/vi/VIDEO_ID/0.jpg - Large
				http://i3.ytimg.com/vi/VIDEO_ID/1.jpg - Cap 1
				http://i3.ytimg.com/vi/VIDEO_ID/2.jpg - Cap 2
				http://i3.ytimg.com/vi/VIDEO_ID/3.jpg - Cap 3 
				http://i1.ytimg.com/vi/VIDEO_ID/hqdefault.jpg
				http://i1.ytimg.com/vi/VIDEO_ID/hq1.jpg
				http://i1.ytimg.com/vi/VIDEO_ID/hq2.jpg
				http://i1.ytimg.com/vi/VIDEO_ID/hq3.jpg
				*/
				
				posicao = 0; // large
				
				return 'http://img.youtube.com/vi/'+videoID+'/'+posicao+'.jpg';
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			embedPlayer: function(videoID,largura,altura)
			{
				if(videoID == undefined || videoID == ''){ alert('ID do vídeo indefinido!'); return false; }
				if(largura == undefined || largura == ''){ alert('Largura do vídeo indefinida!'); return false; }
				if(altura == undefined || altura == ''){ alert('Altura do vídeo indefinida!'); return false; }
				
				try
				{
					var params = { allowScriptAccess: "always" };
					var atts = { id: "myytplayer" };
					
					swfobject.embedSWF(
						"http://www.youtube.com/v/"+videoID+"&enablejsapi=1&playerapiid=ytplayer",
						"ytapiplayer",
						largura,
						altura,
						"8",
						null,
						null,
						params,
						atts
					);
					
					// esta funcao eh chamada sempre que o player em flash termina de carregar
					onYouTubePlayerReady = function(playerId) 
					{
						// escondemos o loading e pegamos o objeto ytplayer com escopo global
						MRP.Get('loadingPlayer','id').style.display = 'none';
						ytplayer = document.getElementById('myytplayer');
					}

				}
				catch(e)
				{
					alert(e);	
				}
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			play: function()
			{
				ytplayer.playVideo();
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			pause: function()
			{
				ytplayer.pauseVideo();
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			stop: function()
			{
				ytplayer.stopVideo();	
			},
			
			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			clear: function()
			{
				ytplayer.clearVideo();	
			},

			/*
			 * @autor Felipe Marques
			 * @date 31-05-2010
			 *
			 * @method
			 * @access 
			 * @params 
			 * @return 
			*/
			trocaVideo: function(videoID,largura,altura)
			{
				try
				{
					ytplayer.loadVideoById(videoID, 0);
					ytplayer.style.width = largura+'px';
					ytplayer.style.height = altura+'px';
					ytplayer.setSize(largura,altura);
				}
				catch(e)
				{
					alert(e);	
				}
			}



		})

	})
});

/*
 * @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 trechoSelecionado = MRP.Editor.myEditor._getSelection();
		var postData = 'conteudo='+conteudo+'&arquivo='+id+'&trechoSelecionado='+trechoSelecionado;
		
		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: '',
	mostrou: '',

	/*
	 * @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 = '';

			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>';

			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>';
		
		//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;

		if(widget.imagens == null) widget.imagens = new Array();
		if(tamanho == undefined || tamanho == '') tamanho = '80x80';
		
		/*
		 * @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':imagens[i].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,imagens[i].origem);
					}
					
					listaImagens.innerHTML = html;
					
					if(widget.mostrou != 'nao')
					{
						if(html.match(/class\=\"imgEditor[ ]temp\"/gi)) alert('Existem imagens temporárias na listagem.');
						widget.mostrou = 'nao';
					}
					
				}
				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,origem)
	{
		// ok
		if(origem == 'banco')
		{
			var html = '<span class="imgEditor">';
				html += '<a href="javascript:;" ondblclick="MRP.Editor.Widget.insertFoto.editaFoto(\''+file_id+'\',\''+file_name+'\')" title="Imagem atrelada a este conteúdo."><img alt="'+file_name+'" title="Imagem atrelada a este conteúdo." 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>';
		}
		else
		{
			var html = '<span id="imagemTemporaria" class="imgEditor temp">';
				html += '<a href="javascript:;" ondblclick="MRP.Editor.Widget.insertFoto.editaFoto(\''+file_id+'\',\''+file_name+'\')" title="Imagem Temporária"><img alt="'+file_name+'" title="Imagem Temporária" 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>';
		}
		
		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(tamanho == undefined || tamanho == '') tamanho = '80x80';
		
		if(imagem.origem == 'banco')
		{
			// monto o src da imagem que sera inserida no editor
			var src = MRP.Config.HOST_PUB+imagem.nomeDominio+'/arquivosUpload/';
				src += imagem.file_id;
				src += tamanho;
				src += '.';
				src += imagem.file_type;
				src += '?time='+time;
				src += '&tamanho='+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){
				
				console.log(widget.action);
				console.log(data.responseText);
				
				
				// 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 = 'MODULO.'+nome_metodo+' = '+metodo;
	eval(estrutura);
}
