$(function()
	{
		XMLHacks.link();
	});

var code2string = function(code)
	{
		if(typeof(code) == 'number')
		{
			code = [code];
		}
		
		var str = '';
		for(i=0;i<code.length;i++)
		{
			str += String.fromCharCode(code[i]);
		}
		return str;
	};

var area = 
	{
		callback:
			{
				onFadeIn: function()
					{
						IEHacks.fixAllFonts('#main');
					},
				onFadeOut: function(url)
					{
						window.location.replace(url);
					}
			},
		fadeIn: function(callback)
			{
				$('#rowsHolder').each(function(idx, item)
					{
						$(item).data('bkp', {'min-height': $(this).css('min-height')});
						$(item).data('intervalId', setInterval(function()
							{
								if($(item).css('min-height') != $(item).data('bkp')['min-height']) 
								{
									clearInterval($(item).data('intervalId'));
									$('#texto').stop().animate({opacity: '1'}, 1000);
								}
							}, 500));
					});
					
				$('#main').animate({opacity: '1'}, 1500, callback||this.callback.onFadeIn);
			},
		fadeOut: function(url, callback)
			{
				var _this = this;
				$('#main, #menu, #texto').css('filter', 'alpha(opacity=100)').animate({opacity: '0'}, 1000, callback||function()
					{
						_this.callback.onFadeOut(url);
					});
			}
	}

var floating = 
	{
		containerId: null,
		containerTop: null,
		lastDocTop: null,
		disabled: false,
		
		easing: 'easeOutQuint',
		duration: 1500,
		
		scroll: function(top, duration, callback, element)
			{
				if (!this.containerTop) 
				{
					this.getContainerTop(element||this.containerId);
				}
				var docTop = $(document).scrollTop();
				
				var limit = $('#footer').offset().top - $('#texto').outerHeight() - $('#menu').outerHeight();
				if(top || (docTop > this.containerTop) || (this.lastDocTop > docTop)) 
				{
					$(this.containerId).stop().animate
						(
							{
								top: (top || ((docTop < this.containerTop) ? this.containerTop :  (docTop > limit) ? limit : docTop)) + 'px',
								opacity: 1
							}, 
							{
								easing: (top ? null : this.easing),
								duration: duration || this.duration,
								queue: false,
								complete: (typeof callback == 'function') ? callback : null
							}
						);
				}
				this.lastDocTop = docTop;
			},
		reset: function()
			{
				$(this.containerId).stop().css('top', this.containerTop + 'px');
			},
		getContainerTop: function(element)
			{
				this.containerTop = $(element).position().top;
			},
		init: function(element)
			{
				var _this = this;	
				
				this.containerId = element;
				if(element && !this.containerTop) 
				{
					this.disabled = true;
					setTimeout(function()
						{
							_this.disabled = false;
							_this.getContainerTop(element);
							_this.scroll();
						}, 200);
				}
				
				$(window).bind('scroll resize',function()
					{
						if(!_this.disabled) _this.scroll();
					});
			}
	};

var modal =
	{
		timeout: null,
		lastSelector: null,
		msg: function(msg)
			{
				return '<div id="modalBox"><table><tr><td class="item_titulo">'+msg+'</td></tr></table>';  
			},
		wait: function()
			{
				return '<div id="modalBox"><table><tr><td class="item_titulo">Carregando ... </td><td><img src="'+_PHP_.incroot+'img/home/acoes/loading.gif" alt=""/></td></tr></table>';  
			},
		erro: function()
			{ 
				return '<div id="modalBox"><table><tr><td class="item_titulo">Erro ao se comunicar com o servidor, por favor tente novamente.</td></tr></table>';
			},
		show: function(selector, type, message)
			{
				this.hide(true);
				$(selector).block
					({
						message: this[type](message),
						centerX: true, 
						centerY: true,
						width: '100px'
					});
				if(type === 'erro' || type === 'msg') this.timeout = setTimeout(this.hide, 5000)
				this.lastSelector = selector;
			},
		hide: function(internal)
			{
				clearTimeout(this.timeout);
				if(!internal)
				{
					$('#modalBox').fadeOut(function()
						{
							$(modal.lastSelector).unblock();		
						});
				}
				else
				{
					$(modal.lastSelector).unblock();
				}
				
			}
	};

function loadPage(page, url, callback)
{
	$("#rows").load
		(
			url+page,
			null,
			function(responseText, textStatus, XMLHttpRequest)
			{
				//$("#rows")[0].scrollTop = 0;
				callback(responseText, textStatus, XMLHttpRequest);
			}
		);
}

function loadStartPage(page, url, hasText)
{
	modal.show('#main', 'wait');
	
	loadPage(page, url, function(responseText, textStatus, XMLHttpRequest)
		{
			modal.hide();
			
			if(textStatus != 'success')
			{
				modal.show('#main', 'erro');
				if(hasText) $('#bt_texto').hide();
				$('#pager').hide();
			}
			else
			{
				$("#rows").fadeIn("slow");
			
				if(hasText)
				{
					collapses.collapsable
						({
							bt_id: '#bt_texto',
							content_id: '#collapsable',
							images: ['arrow_up', 'arrow_down'],
							speed: 'normal'
						});
				}
			}
		});
}

var XMLHacks = 
	{
		link: function()
			{
				$('a[@rel~="external"]').attr('target', '_blank');
			}
	};

var IEHacks = 
	{
		fixAllFonts: function(element)
			{
				this.ifIE(7, function()
					{
						IEHacks.fixFonts(element);
					});
			},
		fixAllPNG: function()
			{
				this.ifIE([5,6], function()
					{
						$('img[@src$=.png]').each(function(index, element)
							{
								IEHacks.fixPNG(element);
							});
					});
			},
		fixFonts: function(element)
			{
				$(element).css('filter', null);
			},
		fixPNG: function(image)
			{
				$(image).css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=image, src="'+$(image).attr('src')+'", sizingMethod="scale");');
				$(image).attr('src', _PHP_.incroot+'js/extjs/ext-2.1/resources/images/default/s.gif');
				return true;
			},
		ifIE: function(version, callback)
			{
				if(typeof version == 'number') version = [version, version];
				var ie = parseInt($.browser.version);
				if($.browser.msie && (ie >= parseInt(version[0]) && ie <= parseInt(version[1])) && typeof callback == 'function')
				{
					callback(ie);
				}
			}
	};

function config()
{
	$.blockUI.defaults =
		{ 
		    pageMessage: '', 
		    elementMessage: '',
		    overlayCSS:  {}, 
		    pageMessageCSS: {}, 
		    elementMessageCSS: {}, 
		    displayBoxCSS: { width: '200px', height: '100px', top:'50%', left:'50%' }, 
		    ie6Stretch: 1, 
		    allowTabToLeave: 0, 
		    closeMessage: 'Click to close', 
		    fadeIn: 1, 
		    fadeInTime: 300, 
		    fadeOut: 1, 
		    fadeOutTime: 300 
		};
	
	$.ajaxSetup
		({
			async: true,
			cache: false,
			type: 'POST'/*,
			beforeSend: function(XMLHttpRequest)
				{
					$('#middle_right').block();
				},
			success: function(data, textStatus)
				{
					$('#middle_right').unblock();
				},
			error: function(XMLHttpRequest, textStatus, errorThrown)
				{
					$('#middle_right').unblock();
					$(modal.erro()).displayBox();
				}*/
		});
		
	collapses.images = ['arrow_up', 'arrow_down'];
}

var collapses =
{
	images: null,
	set: function(ids, callback)
		{
			for(var idx in ids)
			{
				this.collapsable
					({
						bt_id: '#'+ids[idx]+'_bt',
						content_id: '#'+ids[idx],
						speed: 'normal',
						fieldset:
							{
								id: '#'+ids[idx]+'_fieldset',
								'class': 'collapsed'
							}
					});
			}
			
			if(typeof callback == 'function') callback();
		},
	collapsable: function(params)
		{
			var _this = this;
			
			$(params.bt_id).click(function(event)
				{
					event.preventDefault();
					$(params.content_id).slideToggle(params.speed, function()
						{
							var image = $(params.bt_id);
							var images = params.images||_this.images;
							image.attr('src', _PHP_.incroot+'img/home/acoes/'+((image.attr('src').match(images[0]) || (image.css('filter') && image.css('filter').match(images[0]))) ? images[1] : images[0])+'.png');
							
							IEHacks.ifIE([5,6], function()
								{
									IEHacks.fixPNG(image);
								});
							
							if(params.fieldset)
							{
								$(params.fieldset.id).toggleClass(params.fieldset['class']);
							}
						});
				});
		}
}
