$(document).ready(function(){
	$(".uiAccordion").accordion();
	$(".uiTabs").tabs();
	$(".uiDialog").dialog({autoOpen: false,modal: true, draggable:false, height: 500,width: 800});
	$(".uiInput").customInput();
	$(".form-field").focus(function() {
		$("div.form-info").hide();
		if (!$("div."+ $(this).attr('id')).next("div").hasClass("form-error")) 
			$("div."+ $(this).attr('id')).show();
	});
	$(".form-field").blur(function() { $("div."+$(this).attr('id')).hide(); });
	uiMenu();
	uiHolder();	
	uiScrollable(".ui-scrollable");
	//$(window).bind('resize',function() { setTimeout(uiBackground, 1000); });
	setTimeout( function() { $(".content").fadeIn('normal'); $(".background").fadeIn('slow'); $(".dynamic-content").fadeIn('normal'); }, 1000);
});

function uiDialog(url, title, width, height) {
	$("#uiDialog").dialog('destroy');
	$("#uiDialog").dialog({autoOpen: false,modal: true, draggable:false, height: 500,width: 800});
	if (width > 0)
		$("#uiDialog").dialog('option', 'width', width);
	if (height > 0)
		$("#uiDialog").dialog('option', 'height', height);
	$("#uiDialog").dialog('option', 'title', title);
	$("#uiDialog").html('<div id="uiDialogLoading"></div><iframe id="uiDialogFrame" width="100%" height="99%" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" style="margin:0; padding:0; border:none;" />');
   	$("#uiDialogFrame").attr("src", url);
	$("#uiDialog").dialog('open');
   	return false;	
}

function uiMessage(message, title, width, height) {
	if (width > 0)
		$("#uiDialog").dialog('option', 'width', width);
	if (height > 0)
		$("#uiDialog").dialog('option', 'height', height);
	$("#uiDialog").dialog('option', 'title', title);
	$("#uiDialog").html(message);
	$("#uiDialog").dialog('open');
   	return false;	
}

function uiHideSidebar() {
	$("#secondary").css('display','none');
	$("#primary").css('width','964px');
	$("#primary").css('float','none');
}

function go_to (target, href) { 
	try { 
		target.location = href; 
	} 
	catch (e) { 
	
	} 
}

function uiTinymce(id , baseurl) {
$(document).ready(function(){
	$("#" + id + "").tinymce({
		script_url: baseurl+'include/tinymce/tiny_mce.js', theme: "advanced", plugins : "media,paste",
		theme_advanced_buttons1: "cut,copy,pasteword,|,undo,redo,|,uiimage,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,formatselect,|,cleanup,code",
		theme_advanced_buttons2: "", theme_advanced_buttons3: "", theme_advanced_buttons4: "",
		theme_advanced_toolbar_location: "top", theme_advanced_toolbar_align: "left", theme_advanced_statusbar_location: "bottom",
		theme_advanced_resizing: true, theme_advanced_blockformats: "p,h2,h3,h4,h5,h6",
		content_css: "", relative_urls: false, remove_script_host: false, document_base_url: baseurl,
		setup: function(ed) {
			ed.addButton('uiimage', {
				title : 'Imagem',
				image : baseurl+'include/images/uiimage.gif',
				onclick : function() {
					ed.focus();
					uiDialog( baseurl + '?/image/post/' + $("#category_image").val() + '/' + id , 'Imagem' , 600 , 500 );
				}
			});
		}
	});
});
}

function uiMenu() {
	$('ul.navigation ul:not(.active)').hide();
	$('ul.navigation li.active').parent('ul').show();
	$('ul.navigation li a').click(
	function() {
		var checkElement = $(this).next();
		var href = $(this).attr('href');
		if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
			//checkElement.slideUp('normal');
			go_to (self, href);
			return false;
		}
		if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
			$('ul.navigation ul:visible').slideUp('normal');
			//checkElement.slideDown('normal');
			go_to (self, href);
			return false;
		}
	}
	);
}

function uiHolder() {
	$("div.holder:first").fadeIn("slow");
	$("ul.holder-links a").click(
	function() {
		var holderID = $(this).attr('href');
		$("div.holder").fadeOut();
		$("ul.holder-links a").removeClass('active');
		$(holderID).fadeIn();
		$(this).addClass('active');
	});
}

function uiBackground() {
	$(".background > img").hide();
	var vpw = $(window).width();
	var vph = $(window).height();
	var imgw = $(".background > img").width();
	var imgh = $(".background > img").height();
	var resw = 0; var resh = 0; var rest = 0; var resl = 0;
	if ( (vpw / vph) < ( imgw / imgh)) {
		resh = vph;
		resw = (vph * imgw) / imgh;
	} else {
		resw = vpw;
		resh = (vpw * imgh) / imgw;
	}
	//resl = (vpw-resw) / 2;
	//rest = (vph-resh) / 2;
	$(".background").css('width',vpw+'px');
	$(".background").css('height',vph+'px');
	$(".background > img").attr('width',resw);
	$(".background > img").attr('height',resh);
	$(".background > img").css('top',rest);
	$(".background > img").css('left',resl);
	$(".background > img").fadeIn('slow');
}

function uiScrollable(wrapper_id) {
	// Get jQuery elements
	
	var wrapper    = $(wrapper_id);
	var scrollable = $(wrapper_id + " ul");
	var showTooltip = false;
	var scrollableWidth = 0;
	wrapper.css ({width: ($(window).width() - 220) + 'px'});
	scrollable.find('li').each(function(){ scrollableWidth = scrollableWidth + 270; });
	scrollable.css({width: scrollableWidth + 'px'});	
	
	// Hide images until they are not loaded
	scrollable.hide();
	var loading = $('<div class="loading">Carregando...</div>').appendTo(wrapper);
	
	// Set function that will check if all images are loaded
	var interval = setInterval(function() {						
		var images = scrollable.find('img');
		var completed = 0;
		// Counts number of images that are succesfully loaded
		images.each(function(){
			if (this.complete) { 
				completed++;
			}
		});
		if (completed == images.length){
			clearInterval(interval);
			// Timeout added to fix problem with Chrome
			setTimeout(function(){
				loading.hide();
				// Remove scrollbars
				wrapper.css({overflow: 'hidden'}); 
				scrollable.fadeIn('normal', function(){
					enable();
				});
			}, 1000);
		}
	}, 100);
	
	function enable(){
  		// height of area at the top at bottom, that don't respond to mousemove
  		var inactiveMargin = 100;
		// Cache for performance
		var wrapperWidth = wrapper.width();
		var wrapperHeight = wrapper.height();
		// Using outer height to include padding too
		var scrollableWidth = scrollable.outerWidth() + 2*inactiveMargin;
		// Do not cache wrapperOffset, because it can change when user resizes window
		// We could use onresize event, but it's just not worth doing that
		// var wrapperOffset = wrapper.offset();
		// Create a invisible tooltip
		if (showTooltip) {
		var tooltip = $('<div class="ui-scrollable-tooltip"></div>')
			.css('opacity', 0)
			.appendTo(wrapper);
			// Save menu titles
			scrollable.find('a').each(function(){
				// The "data" function attaches custom data to an element
				$(this).data('tooltipText', this.title);
			});
			// Remove default tooltip
			scrollable.find('a').removeAttr('title');
			// Remove default tooltip in IE
			scrollable.find('img').removeAttr('alt');   
		}
		var lastTarget;
		//When user move mouse over menu
		wrapper.mousemove(function(e){
			// Save target
			lastTarget = e.target;
			var wrapperOffset = wrapper.offset();
			if (showTooltip) {
				var tooltipLeft = e.pageX - wrapperOffset.left;
				// Do not let tooltip to move out of menu.
				// Because overflow is set to hidden, we will not be able too see it
				tooltipLeft = Math.min(tooltipLeft, wrapperWidth - 75); //tooltip.outerWidth());
				var tooltipTop = e.pageY - wrapperOffset.top + wrapper.scrollTop() - 40;
				// Move tooltip under the mouse when we are in the higher part of the menu
				if (e.pageY - wrapperOffset.top < wrapperHeight/2){
					tooltipTop  = 80;
				}
				tooltip.css({top: tooltipTop, left: tooltipLeft});                          
			}
			// Scroll menu
			var left = (e.pageX -  wrapperOffset.left) * (scrollableWidth - wrapperWidth) / wrapperWidth  - inactiveMargin;
			
			if (left < 0){
				left = 0;
			}
			wrapper.scrollLeft(left);
		});
		
		// Setting interval helps solving perfomance problems in IE
		var interval = setInterval(function(){
			if (!lastTarget) return;    
			if (showTooltip) {
				var currentText = tooltip.text();
				
				if (lastTarget.nodeName == 'IMG'){
				// We've attached data to a link, not image
				var newText = $(lastTarget).parent().data('tooltipText');
				// Show tooltip with the new text
				if (currentText != newText) {
					tooltip
					  .stop(true)
					  .css('opacity', 0)
					  .text(newText)
					  .animate({opacity: 1}, 1000);
					}
				}
			}
		}, 200);
		
		// Hide tooltip when leaving menu
		wrapper.mouseleave(function(){
			lastTarget = false;
			if (showTooltip) {
				tooltip.stop(true).css('opacity', 0).text('');
			}
		});
		var activeA = scrollable.find('a.active').offset();
		if (activeA.left > 0)
			wrapper.scrollLeft(activeA.left);
	}
}
