var Use = window.Use = function() { return new Use(); };

Use.version = '3.1.9';

var useButton, useMenu, useComboBox, useComponent, useDataGrid, useExternalLink, useEditLink, useForm,
useImage, useImageShow, useJsonEncode, usePanel, useAjax, useRequest, useTab, useTemplate,
useTreeFile, usePng, useSwf, useEdit, useFX;


var pa = function(o){
	var debug = '';
	for (var i in o){
		debug+= i+" -> "+o[i]+"\n";
	}
	alert(debug);
};

//-----------------------------------------------------------------------/ Use.debug	
var pe = function(obj){
	var metodos = '';
	var atributos = '';
	var debug = '[--print Object-------------------------------------------> Agoeiro - version:]<br/>';
		for (var i in obj){
			if(typeof(obj[i])=='function'){
			metodos+= '<b>'+i+":</b> <i>("+(typeof(obj[i]))+")</i>  <br/> <b>-) </b>"+obj[i]+" <b>(-</b>\n<br/>";
			} 
			else {
			atributos+= '<b>'+i+":</b> <i>("+(typeof(obj[i]))+")</i>  <br/> <b>-) </b>"+obj[i]+" <b>(-</b>\n<br/>";						
			}
		}
	debug += '[----------------------------------------------------------------------------------> <b>Atributos</b> ]<br/>';
	debug += atributos;
	debug += '[----------------------------------------------------------------------------------> <b>Metodos</b> ]<br/>';
	debug += metodos;			
	debug += '[<---------------------------------------------------------------------------------]<br/>';
	
	$("#use-debug").remove();
	$("body").prepend('<div id="use-debug"></div>');
	
	$('#use-debug').html(debug).css({ 'border': '3px', 
								'border-style': "solid", 
								'border-color':'#c8560e', 
								'background-color':'#ddf2f8', 
								'margin':'50px', 
								'padding':'20px',
								'display':'block'
								});
						
};
var ps = function(stg){
	var debug = '[--print String--'+(++Use.psCont)+'---------------------------------------- Agoeiro - vers�o: -->|<br/>';
			debug+= stg;
	debug += '<br/>|<------------------------------------------------------------------------]<br/>';
	$("#use-debug").remove();
	$("body").prepend('<div id="use-debug"></div>');
	jQuery('#use-debug').html(debug).css({ 'border': '3px', 
								'border-style': "solid", 
								'border-color':'#7cc80e',
								'background-color':'#ddf2f8', 
								'margin':'50px', 
								'padding':'20px', 
								'display':'block'										
								});
};

	function Menu() {
	   var menuItem = $('.menu-horizontal li');
	   for (var i=0; i< menuItem.length; i++) {
	      if(menuItem[i].className == "menu")
	      {
		  	var item = menuItem[i];	
			$(item).hover(function(){ 
				$(this).find('ul').css({ display: "block"});
				
					$(this).find('li').hover(function(){ 
					  $(this).addClass("sub-menu-hover"); 
					},function(){ 
					  $(this).removeClass("sub-menu-hover"); 
					});
			},function(){ 
				$(this).find('ul').css({ display: "none"});
			});
	      }
	   }
	}
	
/**
 * useExternalLink();
 * Prepara todos os links identificados com rel="external" para abrir em uma nova janela
 */
useExternalLink =  function(){
	jQuery("a[rel^='external']").attr('target','_blank');
};


(function(){
	/**
	 * NOTDOC
	 * @param {Object} selector
	 */
	window.Use.Component = function(selector) {
		return new Use.Component.$(selector);
	};	
	Use.Component.prototype = {
		//Configura a url que deve ser acessada no servidor para obter dados
		baseUrl: function(){
				var baseUrl = location.href;
				var baseUri = baseUrl.match(/(https?:\/\/)([\-\w.]+)+(:\d+)?(\/([\-\w.]+)?)?/i);
            	var url = baseUri[2];
            	
            	if(url == 'localhost' || url == '127.0.0.1'){
            		baseUrl = baseUri[0]; 
            	}
            	else{
            		baseUrl = baseUri[1] + baseUri[2];
            	}			

            return baseUrl;	
		},		
		baseUri: function(){
			return location.href;
		},
		view: function(){
			return this.$[0];
		}				
	};
	useComponent = window.Use.Component;
	
	
	
	window.Use.Fx = function(index) {
		return this instanceof Use.Fx ? this.init(index) : new Use.Fx(index);
	};
	Use.Fx.prototype = {
		init: function(index){ 
			return this;
		},
		alert:function(text, title, buttonOK, modal){
		
			jQuery('#use').prepend('<div id="dialog" title="'+title+'">'+text+'</div>');
			
			jQuery("#dialog").dialog({
					bgiframe: true,
					modal: true,
					buttons: {
						Ok: function() {
							$(this).dialog('close');
						}
					}
				});
		},		
		jQuery:function(action){
			eval("(" + action + ")");
		}		
	};
	useFx = window.Use.Fx;	
	
	/**
	 * Popula combobox(select) utilizando ajax
	 * 
	 * O primeiro argumento deve ser a id do combobox inical da cadeia de
	 * seletores, seguido da url onde deve ser recuperado os dados para
	 * popular o combobox seguinte chamado de target.
	 * 
	 * O valor do combobox selecionado e enviado automaticamente como parametros 
	 * do metodo GET bem como pode ser enviado outros parametros alem atraves do
	 * metodo data(}.
	 * 
	 * Se nao deseja envir nenhum parametro extra nao e necessario utilizar o metodo
	 * data.
	 * 
	 * Pode ser enviar como data uma acao que deve ser disparada apos o retorna 
	 * do evento ajax ser executado.
	 * 
	 * EXEMPLO:
	   useComboBox('#categorySelect')
			.url('select-search.php')
			.data( { "type": "true", "estado":"SP" , meuEvento: "nomeDaFuncaoSemApas" } )
			.target('#elementSelect')
			
			
			.url('select-search.php')
			.data( { "type": "true", "cidade":"Santos" } )
			.target('#attributeSelect');
	 * 
	 * @param {String} 
	 */
	window.Use.ComboBox = function(id) {
		return this instanceof Use.ComboBox ? this.init(id) : new Use.ComboBox(id);
	};
	Use.ComboBox.prototype = {
		init: function(id){ 
			this._id = jQuery(id);
			this._data = {};
			return this;
		},

		url: function(url){ 
			this._url = this.baseUrl() + url;
			return this;
		},
		data: function(data){ 
			this._data = data;
			return this;
		},
		target: function(id){ 
			this._target = jQuery(id);

	       this._id.selectChain({
	            target: this._target,
	            url: this._url ,
	            data: this._data
	        }).trigger('change');

			this._id = this._target;
			return this;
		},
		/**
		 * Recebe uma url onde deve buscar dados para popular o combobox com a opçao de
		 * elementos desativados, permitindo que seja selecionado somente itens que tenham 
		 * elementos contidos na base de dados.
		 * 
		 * Exemplo:
		 * useComboBox("#estado").createOptionsItemsDisable("/busca/simples/populateestado");
		 * useComboBox("#estado").createOptions("/busca/simples/populateestado");
		 * 
		 * @param {Object} url
		 */
		createOptionsItemsDisable : function(url, info, useData){
			
			var id = this._id;
			
			var info = info || 'selecione...';
			
			var useData = useData || false;
			
			jQuery.ajax({ 
				  type: "GET", 
				  url: this.baseUrl()+url, 
				  success: function(res){ 			
		
					var option = '<option value="">'+info+'</option>';
					var obj = eval("(" + res + ")");
			
					for (var i in obj){
						
						///useData ? value = obj[i].data : value = i;  // NOTFINAL
						value = i;
						if(obj[i] == 1){
							option +=  '<option value="' + value + '">' + i + '</option>';
						}
						else{
							option +=  '<option value="' + value + '" disabled="true">' + i + '</option>';
						}
					}
					id.html(option);
				}
			}); 			
		},
		createOptions : function(url, info){
			
			var id = this._id;
			
			var info = info || 'selecione...';
			
			jQuery.ajax({ 
				  type: "GET", 
				  url: this.baseUrl()+url, 
				  success: function(res){ 			
		
					var option = '<option value="">'+info+'</option>';
					var obj = eval("(" + res + ")");
			
					for (var i in obj){
						option +=  '<option value="' + i + '">' + i + '</option>';
					}
					id.html(option);
				}
			}); 			
			
		}				
	};
	
	//jQuery.extend(Use.ComboBox.prototype, Use.Component.prototype , {});			
	useComboBox = window.Use.ComboBox;		

	/**
	 * Prepara acoes para o componente Tabs
	 * 
	 * @param {String} 
	 */
	window.Use.Tab = function(index) {
		return this instanceof Use.Tab ? this.init(index) : new Use.Tab(index);
	};

	Use.Tab.prototype = {
		init: function(index){ 
			index = "#"+index;
			this.$ = jQuery(index+" > ul").tabs();
			jQuery(index).css({display: "block"});	
			return this;
		},

		disable: function(orderTabs){
			for (var i in orderTabs){
				this.$.tabs("disable", orderTabs[i]);
			}
			return this;
		},
		active: function(tab){
			this.$.tabs("select", "#use-tab-"+tab);
			return this;
		}
	};

	useTab = window.Use.Tab;
	
	

	/**
	 * Prepara acoes para o componente panel
	 * 
	 * @param {String} 
	 */
	window.Use.Panel = function(id) {
		return this instanceof Use.Panel ? this.init(id) : new Use.Panel(id);
	};
	Use.Panel.prototype = {
		init: function(id){
			this.panel = id;
			var panel = '#'+id;
		 	//jQuery(panel).css({ display: 'block'});
			jQuery(panel + ' .use-button-tool-toggle').toggle(function(){ 
			  jQuery(panel).removeClass(" use-panel-collapsed"); 
   			  jQuery(panel + ' .use-panel-wrap').css({ display: 'block'});
			},function(){ 
			  jQuery(panel).addClass("use-panel-collapsed"); 
			  jQuery(panel + ' .use-panel-wrap').css({ display: 'none'});
			});
			return this;
		},
		show: function(){
			var panel  = '#'+this.panel;
			jQuery(panel).removeClass("use-panel-collapsed"); 
			jQuery(panel + ' .use-panel-wrap').css({ display: 'block'});
			jQuery(panel + ' .use-button-tool-toggle').unbind()
			jQuery(panel + ' .use-button-tool-toggle').toggle(function(){ 
			  jQuery(panel).addClass("use-panel-collapsed"); 
			  jQuery(panel + ' .use-panel-wrap').css({ display: 'none'});
			},function(){ 
			  jQuery(panel).removeClass("use-panel-collapsed"); 
   			  jQuery(panel + ' .use-panel-wrap').css({ display: 'block'});
			});			  
			return this;
		}
	};
	usePanel = window.Use.Panel;
	

	/**
	 * Prepara acoes para o componente ajax
	 * 
	 * @param {String} 
	 */
	window.Use.Ajax = function(id){
		return this instanceof Use.Ajax ? this.init(id) : new Use.Ajax(id);
	};
	Use.Ajax.prototype = {
		init: function(id){
			this.panel = id;
			return this;
		},
		type: function(type){
			this.type = type;
			return this;
		},
		dataType: function(dataType){
			this.dataType = dataType;
			return this;
		},
		url: function(url){
			this.url = url;
			return this;
		},
		data: function(data){
			this.data = data;
			return this;
		},
		success: function(success){
			this.success = success;
			return this;
		},
		stop: function(stop){
			this.stop = stop;
			return this;
		},
		render: function(){
			jQuery("#loading").ajaxStart(function(){ 
  				$(this).show(); 
			});	
				
			jQuery.ajax({ 
			  type: this.type, 
			  dataType: this.dataType,
			  url: this.url, 
			  data: this.data, 
			  success: this.success
			});		
			
			jQuery("#loading").ajaxStop(function(){ 
  				 //this.stop(this);
				   jQuery(this).hide();
			});

			jQuery("#msg").ajaxSuccess(function(request, settings){
			  $(this).append("<li>Successful Request!</li>"); 
			});			
			
		}
	};
	useAjax = window.Use.Ajax;	
	


	/**
	 * Prepara acoes para o componente Tabs
	useSwf()
		  .src("http://localhost/extras/usefx/form/index")
		  //.version(9,0,28)
		  .flashVars([{"index1":"value1", "index2":"value2"}])
		  //.width("100%")
		  //.height("100%")
		  //.align("middle")
		  .id("index")
		  //.quality("high")
		  //.bgColor("#ffffff")
		  .name("index")
		  //.wmode("transparent") 
		  //.allowFullScreen(true) 
		  //.allowScriptAccess("sameDomain")
		  .show();
	 * 
	 * @param {String} 
	 */
	window.Use.Swf = function(id) {
		return this instanceof Use.Swf ? this.init(id) : new Use.Swf(id);
	};
	Use.Swf.prototype = {
		init: function(id){ 
			this._params = ["type","application/x-shockwave-flash","pluginspage","http://www.adobe.com/go/getflashplayer"];
			this.version(9,0,28);
			return this;
		},
		allowFullScreen: function(value){
			this._params.push("allowFullScreen");
			this._params.push(value);
			return this;
		}, 
		allowScriptAccess: function(value){
			this._params.push("allowScriptAccess");
			this._params.push(value);
			return this;
		}, 
		src: function(value){
			this._params.push("src");
			this._params.push(value);
			return this;
		}, 
		align: function(value){
			this._params.push("align");
			this._params.push(value);
			return this;
		}, 
		menu: function(value){
			this._params.push("menu");
			this._params.push(value);
			return this;
		}, 
		id: function(value){
			this._params.push("id");
			this._params.push(value);
			return this;
		}, 
		name: function(value){
			this._params.push("name");
			this._params.push(value);			
			this._name = name;
			return this;
		}, 
		wmode: function(value){
			this._params.push("wmode");
			this._params.push(value);	
			return this;
		}, 
		quality: function(value){
			this._params.push("quality");
			this._params.push(value);	
			return this;
		}, 
		width: function(value){
			this._params.push("width");
			this._params.push(value);	
			return this;
		}, 
		height: function(value){
			this._params.push("height");
			this._params.push(value);	
			return this;
		}, 
		bgColor: function(value){
			this._params.push("bgColor");
			this._params.push(value);	
			return this;
		}, 
		flashVars: function(value){
			this._params.push("flashVars");
			this._params.push(value);	
			return this;
		}, 
		flashError: function(value){
			var flashError = value || 'Alternate HTML content should be placed here.'
			  	+ 'This content requires the Adobe Flash Player. '
			   	+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
			this._flashError = flashError;
			return this;
		}, 
		version: function(requiredMajorVersion, requiredMinorVersion, requiredRevision){
			// Major version of Flash required
			this.requiredMajorVersion = requiredMajorVersion;
			// Minor version of Flash required
			this.requiredMinorVersion = requiredMinorVersion;
			// Minor version of Flash required
			this.requiredRevision = requiredRevision;
			return this;
		}, 
		render: function(){ 
			var hasProductInstall = DetectFlashVer(6, 0, 65);
			
			// Version check based upon the values defined in globals
			var hasRequestedVersion = DetectFlashVer(this.requiredMajorVersion, this.requiredMinorVersion, this.requiredRevision);
			
			if ( hasProductInstall && !hasRequestedVersion ) {
				// DO NOT MODIFY THE FOLLOWING FOUR LINES
				// Location visited after installation is complete if installation is required
				var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
				var MMredirectURL = window.location;
			    document.title = document.title.slice(0, 47) + " - Flash Player Installation";
			    var MMdoctitle = document.title;
			
		 		//NOTFINAL corrigir parametros
				AC_FL_RunContent(
					"src", "playerProductInstall",
					"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
					"type", "application/x-shockwave-flash",
					"pluginspage", "http://www.adobe.com/go/getflashplayer"
				);
			} else if (hasRequestedVersion) {
				// if we've detected an acceptable version
				// embed the Flash Content SWF when all tests are passed
				AC_FL_RunContent(this._params);
			} else {  
				//flash is too old or we can't detect the plugin
				// insert non-flash content
				document.write( this._flashError);  
				
			}			
		}
	};
	useSwf = window.Use.Swf;


	
	/**
	 * Prepara acoes para o componente Button
	 * 
	 * @param {String} 
	 */
	window.Use.Button = function(id) {
		return this instanceof Use.Button ? this.init(id) : new Use.Button(id);
	};
	Use.Button.prototype = {
		init: function(id){ 
			this.$ = jQuery('#'+id + ' tr:first');
			if($.browser.msie) { 
				$('.use-button').addClass('use-button-ie-bug-fix-1');
			}			
			return this;
		},
		action: function(fnc){
			this.$.bind('click', fnc);
			this.events();
		},
		disable: function(){
			this.$.unbind();
		},
	    events : function(){
			this.$.hover(function() {
				jQuery(this).not('.use-button-disable').addClass('use-button-over');
			}, function() {
				jQuery(this).removeClass('use-button-over use-button-click');
			});
			this.$.click(function() {
				jQuery('.use-button-focus').removeClass('use-button-focus');
				jQuery(this).addClass('use-button-focus');
			});
			this.$.mousedown(function() {
				jQuery(this).not('.use-button-disable').addClass('use-button-click'); });
			this.$.mouseup(function() {
				jQuery(this).removeClass('use-button-over use-button-click');
				});
			return this;
	    }		
	};
	jQuery.extend(Use.Button.prototype, Use.Component.prototype , {
	});		
	useButton = window.Use.Button;
	
	
	
	/**
	 * Ative sub menus para menu horizontal
	 * 
	 */
	window.Use.Menu = function() {
		return this instanceof Use.Menu ? this.init() : new Use.Menu();
	};
	Use.Menu.prototype = {
		init: function(){
		   var menuItem = jQuery('.use-menu-horizontal li');
		   for (var i=0; i< menuItem.length; i++) {
		      if(menuItem[i].className == "menu")
		      {
			  	var item = menuItem[i];	
				jQuery(item).hover(function(){ 
					jQuery(this).find('ul').css({ display: "block"});
					
						jQuery(this).find('li').hover(function(){ 
						  jQuery(this).addClass("sub-menu-hover"); 
						},function(){ 
						  jQuery(this).removeClass("sub-menu-hover"); 
						});
				},function(){ 
					jQuery(this).find('ul').css({ display: "none"});
				});
		      }
		   }
		}			
	};
	useMenu = window.Use.Menu;	


	/**
	 * Prepara acoes para o componente Grid
	 * 
	 * @param {String} 
	 */
	window.Use.DataGrid = function(id) {
		return this instanceof Use.DataGrid ? this.init(id) : new Use.DataGrid(id);
	};
	Use.DataGrid.prototype = {
		init: function(id){ 
			this.id = id;
			return this;
		},
		config: function(config){
			jQuery("#"+this.id).flexigrid(config);
		}
	};
	useDataGrid = window.Use.DataGrid;	


	/**
	 * Prepara acoes para o componente Editor
	 * 
	 * @param {String} 
	 */
	window.Use.Edit = function( ) {
		
		return this instanceof Use.Edit ? this.init() : new Use.Edit();
	};
	Use.Edit.prototype = {
		init: function(){
			this.$ = document.getElementById("use_edit_content_frame");
		},
	    /**
	     * Recupera o objeto Flex para ser manupulado pelo javascript
	     * useEdit().fx().nomeDaFuncaoDeclaradaNoFlex();
	     */
		fx: function(){
	        if (navigator.appName.indexOf ("Microsoft") !=-1) {
				return window['useFxSwf'];
				
	        } else {
	            return document['useFxSwf'];
	        }
	    },
		/**
		 * Cria iframe para mostrar pagina que pode ser visualizada ou editada
		 * @param {Object} baseUrl Caminho de pagina que deve ser aberta
		 */		
		showTinyMCE: function(baseUrl){
			jQuery("#use_edit_content").remove();
			jQuery("body").append('<div id="use_edit_content" style="width:100%;"><iframe id="use_edit_content_frame" src="' + baseUrl + '" scrolling="auto"   marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" marginheight="0" style="overflow:auto; width:100%; display:none; margin-top:0px; z-index:50" onLoad="useEdit().tinyMCE();"></iframe></div>');				
		},
		showEditArea: function(baseUrl){
			jQuery("#use_edit_content").remove();
			jQuery("body").append('<div id="use_edit_content" style="width:100%;"><iframe id="use_edit_content_frame" src="' + baseUrl + '" scrolling="auto"   marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" marginheight="0" style="overflow:auto; width:100%; display:none; margin-top:0px; z-index:50" onLoad="useEdit().editArea();"></iframe></div>');				
		},
		showPreview: function(baseUrl){
			jQuery("#use_edit_content").remove();
			jQuery("body").append('<div id="use_edit_content" style="width:100%;"><iframe id="use_edit_content_frame" src="' + baseUrl + '" scrolling="auto"   marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" marginheight="0" style="overflow:auto; width:100%; display:none; margin-top:0px; z-index:50" onLoad="useEdit().contentPreview();"></iframe></div>');
		},
		config: function(){
			this.fx().hideProgress();
		},

		popup: function(){
			var height = window.document.body.offsetHeight - 139;
			if (window.addEventListener){
				//alert(height);
			}
			else if (window.attachEvent){
				//alert('ie');
			}			
			this.iFrame().useEdit().resizeEdit(height);
		},
		resizeEdit:function (height){
			jQuery("#use_edit_content_text_area_ifr").css({"height": height+"px"});
		},
		
		popupX: function(url, type){

			$(function() {
				$("#dialog").dialog({
					bgiframe: true,
					height: 420,
					width:520,
					modal: true
				});
			});
		},
		toBack: function(){
			jQuery("#fx").css({"height": "62px"});
			jQuery("#use-edit-content-menu").css({"z-index": "10"});
			jQuery("#use_edit_content_frame").css({"display": "block"});
			jQuery("#use_edit_content").css({"display": "block"});
		},
		toFront: function(){
			jQuery("#fx").css({"height": "100%"});
			jQuery("#use-edit-content-menu").css({"z-index": "1000"});
			jQuery("#use_edit_content_frame").css({"display": "none"});
			jQuery("#use_edit_content").css({"display": "none"});
		},
		/**
		 * Adiciona eventos para ajustar tamanho da janela do editor tinyMCE
		 */		
		tinyMCE: function(){ 
			this.resizeTinyMCE();
			
			if (window.addEventListener){
				window.addEventListener("load", useEdit().resizeTinyMCE, false)
			}
			else if (window.attachEvent){
				window.attachEvent("onload", useEdit().resizeTinyMCE)
			}
			
			window.onresize = useEdit().resizeTinyMCE;
			this.toBack();	
			this.config();
		},
		resizeTinyMCE: function(){ 
			var iframeids = ["use_edit_content_frame"];
			if (this.$) useEdit().resizeIframeTinyMCE(iframeids);
			if ((document.all || document.getElementById)){
				var tempobj = document.all ? document.all[iframeids] : document.getElementById(iframeids)
				tempobj.style.display="block"
			}
		},
		resizeIframeTinyMCE: function (frameid){
			var currentfr = this.$
			if (currentfr && !window.opera){
				currentfr.style.display="block";
			}
			height = window.document.body.offsetHeight - 62;
			currentfr.height = height;
			this.popup();
		},
		/**
		 * Adiciona eventos para ajustar tamanho da janela do editor tinyMCE
		 */		
		editArea: function(){ 
			this.resizeEditArea();
			
			if (window.addEventListener){
				window.addEventListener("load", useEdit().resizeEditArea, false)
			}
			else if (window.attachEvent){
				window.attachEvent("onload", useEdit().resizeEditArea)
			}
			
			window.onresize = useEdit().resizeEditArea;
			this.toBack();	
			this.config();
		},
		resizeEditArea: function(){ 
			var iframeids = ["use_edit_content_frame"];
			if (this.$) useEdit().resizeIframeEditArea(iframeids);
			if ((document.all || document.getElementById)){
				var tempobj = document.all ? document.all[iframeids] : document.getElementById(iframeids)
				tempobj.style.display="block"
			}
		},
		resizeIframeEditArea: function (frameid){
			var currentfr = this.$
			if (currentfr && !window.opera){
				currentfr.style.display="block";
			}
			height = window.document.body.offsetHeight - 62;
			currentfr.height = height;
		},


		/**
		 * Adiciona eventos para ajustar tamanho da janela do preview
		 */		
		contentPreview: function(){ 
			this.resizeCaller();
			if (window.addEventListener){
					window.addEventListener("load", useEdit().resizeCaller, false)
				}
				else 
					if (window.attachEvent){
						window.attachEvent("onload", useEdit().resizeCaller)
					}
				window.onresize = useEdit().resizeCaller;
			this.toBack();	
			this.config();
		},
		resizeCaller: function(){ 
			var iframeids = ["use_edit_content_frame"];
			if (this.$) useEdit().resizeIframe(iframeids);
			if ((document.all || document.getElementById)){
				var tempobj = document.all ? document.all[iframeids] : document.getElementById(iframeids)
				tempobj.style.display="block"
			}
		},
		resizeIframe: function (frameid){
			var currentfr = this.$
			if (currentfr && !window.opera){
				currentfr.style.display="block";
			}
			
			height = window.document.body.offsetHeight - 62;
			currentfr.height = height;
		},
		readjustIframe: function (loadevt) {
			var crossevt = (window.event)? event : loadevt
			var iframeroot = (crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
			if (iframeroot) {
				useEdit().resizeIframe(iframeroot.id);
			}	
		},
		loadintoIframe: function (iframeid, url){
			if (document.getElementById) {
				document.getElementById(iframeid).src = url
			}
		},


		iFrame:function (){
			return document.getElementById("use_edit_content_frame").contentWindow;
		},

		/**
		 * Recupera a uri modulo/controle/acao/id do conteudo em edicao
		 * 
		 * @return object
		 */
		requestUri:function (){
			return this.iFrame().requestUri;
		},
		/**
		 * Recupera informacoes e uri do conteudo em edicao 
		 * 
		 * @return object
		 */
		content:function (editorType){
			
			if (editorType == 'wysiwyg') {
				activeEditor = this.iFrame().tinyMCE.activeEditor.id;
				return this.iFrame().tinyMCE.get(activeEditor).getContent();				
			}
			else {
				return this.iFrame().editAreaLoader.getValue('use_edit_content_text_area');
			}
		}

	};
	jQuery.extend(Use.Edit.prototype, Use.Component.prototype , {
	});		
	useEdit = window.Use.Edit;


	/**
	 * Prepara acoes para o componente TreeFile
	 * 
	 * @param {String} 
	 */
	window.Use.TreeFile = function(id) {
		return this instanceof Use.TreeFile ? this.init(id) : new Use.TreeFile(id);
	};
	Use.TreeFile.prototype = {
		init: function(id){ 
			this.id = id;
			jQuery("#"+id).css({display: "block"});	
			return this;
		},
		config: function(c){
			jQuery("#"+this.id).fileTree({ root: c.root, script: c.script, filetype: c.filetype }, function(file) { 
				if(c.action) c.action(file);
			});			
		}
	};
	useTreeFile = window.Use.TreeFile;	


	/**
	 * Prepara acoes para o componente Image
	 * 
	 * @param {String} 
	 */
	window.Use.Image = function(id) {
		return this instanceof Use.Image ? this.init(id) : new Use.Image(id);
	};
	Use.Image.prototype = {
		init: function(id){ 
			this.id = id;
			return this;
		},
		editSize: function(){
			alert('result');
		},
		crop: function(){
			alert('result');
		},
		result: function(result){
			jQuery('#recebe_up_basico').html(result);
		},
		upload: function(form, baseUrl){
		    var iFrame = document.createElement("iframe");
			    iFrame.setAttribute("id", "use-iframe");
			    iFrame.setAttribute("name", "use-iframe");
			    iFrame.setAttribute("width", "0");
			    iFrame.setAttribute("height", "0");
			    iFrame.setAttribute("border", "0");
			    iFrame.setAttribute("style", "width: 0; height: 0; border: none;");
		    
		    form.parentNode.appendChild(iFrame);
		    window.frames['use-iframe'].name = "use-iframe";
		    
		    //Adiciona evento ao iframe
		    var load = function(){
				jQuery("#use-iframe").attr({ 
		          //src: "javascript: window.parent.jQuery('#recebe_up_basico').html();"
		          src: "javascript: window.parent.useImage().result(document.body.innerHTML);"
		        });
				
		        //Remove o iframe
		        setTimeout(function(){
					jQuery('#use-iframe').remove();
					jQuery('#image-show-file-box').fadeOut("slow");
		        }, 150);
		    }
		    
			jQuery('#use-iframe').bind("load", load);
		    
		    //Configura as propriedades do form
		    form.setAttribute("target", "use-iframe");
		    form.setAttribute("action", baseUrl + '/use/imageupload');
		    form.setAttribute("method", "post");
		    form.setAttribute("enctype", "multipart/form-data");
		    form.setAttribute("encoding", "multipart/form-data");
		    form.submit();
		    
			//Acao default disparada antes do iframe entrar em acao
			jQuery('#recebe_up_basico').html('<div style="margin:15px;"><div style="width:25px; float:left;"><img src="http://localhost/shop.rusithy.com.br/public/library/useProject/styles/i/prettyPhoto/loader.gif" alt="" /></div><div style="padding-top:5px; padding-left:4px;">Carregando imagem...</div></div></div>').fadeIn("slow");
		}
	};
	useImage = window.Use.Image;	


	/**
	 * Prepara acoes para o componente ImageShow
	 * 
	 * @param {String} 
	 */
	window.Use.ImageShow = function(id) {
		return this instanceof Use.ImageShow ? this.init(id) : new Use.ImageShow(id);
	};
	Use.ImageShow.prototype = {
		init: function(id){ 
			this.$ = jQuery("#"+id);
			this.events();
			return this;
		},
		events: function(){
			jQuery('.thumb-wrap a').click(function() {
				jQuery('.image-show-focus').addClass('image-show-normal').removeClass('image-show-focus');
				jQuery(this).removeClass('image-show-normal').addClass('image-show-focus');
				zIndex = jQuery('.image-show-display-active').removeClass('image-show-display-active').show().css('z-index');
				imageId = jQuery(this).attr("id");
				
				jQuery('#zoom-'+imageId).addClass('image-show-display-active').css({zIndex: ++zIndex});

			}); 
			
			jQuery('.thumb-wrap a').hover(function() {
				jQuery(this).addClass('thumb-hover');
			}, function() {
				jQuery(this).removeClass('thumb-hover');
			});			
			
		}
	};
	useImageShow = window.Use.ImageShow;	
	
	/**
	 * Recupera dados da base de dados ou processa dados recebidos no formato json
	 * e popula um template
	 * 
	 * @param {String} 
	 * @return Html
	 */
	window.Use.Template = function(id) {
		return this instanceof Use.Template ? this.init(id) : new Use.Template(id);
	};
	Use.Template.prototype = {
		
		/*
		 * Busca dados no servidor para popular o template, ou utiliza os dados 
		 * fornecido em data e renderiza o template
		 */
		render: function(id){
			var tplId = this.tplId;
			var data = this._data;
			var params = this._params;
			id = '#' + id;
			if (this._url) {
				jQuery.ajax({
					url: this._url,
					data: params,
					cache: false,
					dataType: "text",
					success: function(result){
						var data = useObject(result);
						jQuery(id).setTemplateElement(tplId);
						jQuery(id).processTemplate(data);
					}
				})
			}
			else{
				jQuery(id).setTemplateElement(tplId);
				jQuery(id).processTemplate(data);
			}	
		}
	};
	jQuery.extend(Use.Template.prototype, Use.Component.prototype , {
		init: function(tplId){ 
			this.tplId = tplId;
			this._url = null;
			return this;
		}
	});		
	useTemplate = window.Use.Template;		


	/**
	 * NOTDOC
	 * 
	 * @return object Use.Form
	 */
	window.Use.Form = function(id) {
		return this instanceof Use.Form ? this.init(id) : new Use.Form(id);
	};
	Use.Form.prototype = {
		/*
		 * Busca dados no servidor para popular o Form, ou utiliza os dados 
		 * fornecido em data e renderiza o Form
		 */
		render: function(id){
			var formId = this._formId;
			var data = this._data;
			var params = this._params;
			
			if (this._url) {
				jQuery.ajax({
					url: this._url,
					data: params,
					cache: false,
					dataType: "text",
					success: function(result){
						var data = useObject(result);
						var form = document.forms[formId];
						jQuery(form).populate(data)
					}
				})
			}
			else{
				var form = document.forms[formId];
				jQuery(form).populate(data)				
			}	
		}
	};
	jQuery.extend(Use.Form.prototype, Use.Component.prototype , {
		init: function(formId){ 
			this._formId = formId;
			this._url = null;
			return this;
		}
	});		
	useForm = window.Use.Form;	
	

	window.Use.Util = function(id) {
		return this instanceof Use.Util ? this.init(id) : new Use.Util(id);
	};
	Use.Util.prototype = {
		init: function(){ 
			return this;
		}
	};
	
	jQuery.extend(Use.Util.prototype, Use.Component.prototype , {});
	useUtil = window.Use.Util;
	
	
})(window);