var popupTimeoutId;

$(document).ready(function() {
	$('body').append('<div id="tooltiptrack"><div class="top"></div><div class="content"></div><div class="bottom"></div></div>');

	$("#product-grid input[type=checkbox]").click(function(){
		$("#page").val(0);
		$($(this).parent()).find(".sub-filter").remove();
		blockGrid();
		$("#filterForm").submit();
	})
	$("#product-grid .sortoptions a").click(function(){
		$("#page").val(0);
		$("#order").val($(this).attr("rel"));
		blockGrid();
		$("#filterForm").submit();
		return false
	})
	$("#product-grid .pagination a").click(function(){
		if($(this).hasClass("arrowinactive")){
			return false
		}

		if($(this).attr("rel") !== "all"){
			$("#page").val($(this).attr("rel"));
		} else {
			$("#page").val(0);
			$("#limit").val($("#total").val());
		}
		blockGrid();
		$("#filterForm").submit();
		return false
	})
	
	customTrackTooltip();
});

function unblockGrid(){
	$("#product-grid").unblock()
}

function blockGrid(){
	$productgrid = $('#product-grid');
	
	$productgrid.block({ message: '<img src="' + template_url + '/img/preloaders/large.gif" /><br />Carregando',
		css: {
			width: '100%',
			height: '88%',
			top: '43%',
			left: 0,
			border: 'none',
			padding: '0',
			backgroundColor: '#fff',
			opacity: .5,
			color: '#000'
		},
		overlayCSS:  {
			backgroundColor: '#fff',
			opacity: 0.9
		}
	  });
}

function customTrackTooltip() {
	$('.tooltiptrack').hover(
		function(e) {

			// check to see if a timeout has already been started
			if (popupTimeoutId) {
				clearTimeout(popupTimeoutId);
				popupTimeoutId = null;
			}

			$tooltip = $('#tooltiptrack');
			var id = '#tt_' + $(this).attr('id').match(/[a-zA-Z0-9]+$/);

			// position tooltip on element
			$('#tooltiptrack .content').html($(id).html());
			var h = $tooltip.height();
			var w = $tooltip.width();
			var offset = $(this).offset();
			$('#tooltiptrack').css({ top: (offset.top - (h - 40)) + 'px', left: (offset.left - ((w / 2) - $(this).width() / 2)) + 'px'}).fadeIn('fast');
		},
		function() {
			popupTimeoutId = setTimeout(hideTooltip, 200);
		}
	);

	$('#tooltiptrack').hover(
		function() {
			// check to see if a timeout has already been started
			if (popupTimeoutId) {
				clearTimeout(popupTimeoutId);
				popupTimeoutId = null;
			}
		},
		function() {
			popupTimeoutId = setTimeout(hideTooltip, 200);
		}
	);
}

function hideTooltip(){
	$('#tooltiptrack').fadeOut('fast');
	if ($.browser.msie && $.browser.version == "6.0") {
		$('#dd_go_h').show();
		$('#dd_producttype_h').show();
		$('#dd_gender_h').show();
		$('#dd_category_h').show();
		$('#dd_sub_category_h').show();
	}
}
