// Build Tooltip divs and attach mouse-handling and loading functions
function InitTooltips() {
	$$( '.tt' ).each( function(item) {
		tooltip = document.createElement( "span" );
		Element.extend(tooltip);
		tooltip.addClassName("tooltip_n");
		item.appendChild( tooltip );
	} );
}

// Parse URLs and attach data-URL to tooltips
function InitRaTooltips() {
	$$( '.tt_ra' ).each( function(item) {
		link = item.readAttribute('href');
		regex = /char_id=(\d+)/;
		if( result = regex.exec(link) ) {
			item.char_id = result[1];
		}
		regex = /event_type_id=(\d+)/;
		if( result = regex.exec(link) ) {
			item.event_type_id = result[1];
		}
		Event.observe( item, "mouseover", function(e) {
			element = Event.element(e);
			element.addClassName('hover');
			tooltip = element.down(".tooltip_n");
			if ( !( tooltip.hasClassName("loading") || tooltip.hasClassName("loaded") ) ) {
				tooltip.addClassName("loading");
				new Ajax.Updater(
					tooltip,
					"/accounts/" + element.char_id + "/recent_atts.inc?event_type_id=" + element.event_type_id,
					{
						method:'get',
						onComplete: function(transport) {
							positionTooltip(tooltip, e);
							tooltip.removeClassName("loading");
							tooltip.addClassName("loaded");
						}
					}
				);
			}
		} );
		
		Event.observe( item, "mouseout", function(e) {
			this.removeClassName('hover');
		} );
		
		Event.observe( item, "mousemove", function(e) {
			offset = Element.cumulativeOffset(item);
			tooltip = item.down(".tooltip_n");
			positionTooltip(tooltip, e);
		} );
		
	} );
}

function positionTooltip(tooltip, e) {
	x = Event.pointerX(e);
	if( x + Element.getWidth(tooltip) + 5 > document.viewport.getWidth() ) {
		x = document.viewport.getWidth() - Element.getWidth(tooltip) - 5;
	}
	tooltip.setStyle( {
		left: x - offset[0] + 5 + "px",
		top: Event.pointerY(e) - offset[1] - Element.getHeight(tooltip) - 5 + "px"
	} );	
}

function InitAutoSubmit() {
	$$( '.auto_submit' ).each( function(item) {
		select = item.down( 'select' );
		if( select ) {
			Event.observe( select, "change", function(e){ item.submit(); } )
		}
		submit = item.down( 'input[type="submit"]' );
		if( submit ) {
			submit.remove();
		}
	} );
}

function change_rows(t, r, s)
{
	tbl = $(t);
	r.each( function(i) {
		tbl.rows[i].setStyle( {display: s} );
	} );
}

Event.observe( window, 'load',
	function() { 
		InitAutoSubmit();
		InitTooltips();
		InitRaTooltips();
	}
);
