var topic = '';

$(document).ready( function() {	
	$("#throbber").ajaxStop( function() { $(this).hide(); } );
	$("#mantis_throbber").hide();
	
	$("#mantis_ticker").hide();
	$("#login_status").hide();
	
	$("#bugs_new").hide();
	$("#bugs_updated").hide();
	$("#bugs_assigned").hide();
	
	$("#mantis_login").submit( mantisLogin );
	$("#mantis_logout").click( mantisLogout );
	
	$("#mantis_log").attr( 'href', '/gaben_api/mantis/gaben_mantis.php?req=log' );
	$("#mantis_log").fancybox( { 'hideOnContentClick': false, 'frameWidth' : 900, 'frameHeight' : 600 } );
	
	setTimeout( getTopic, 1 );
	initializeMantisTicker();
	
} );

function getTopic() {
	$.get( "/gaben_api/irc/gettopic.php", null, function( response )
		{
			var obj = $.evalJSON( response );

			if ( obj.topic != topic && topic != '' ) {
				$("#topic").customFadeOut( "slow" );
				setTimeout( function()
					{
						// New topic
						$("#topic").html( colorize( obj.topic ) );
						if ( obj.nickname ) {
							$("#topic").append('<br />(set by ' + obj.nickname + ')');
						}						
						$("#topic").customFadeIn( "slow" );
						$("#throbber").hide();
					}
					,800
				);
			} else if ( topic == '' ) {
				// Initial fade
				$("#topic").hide();
				$("#topic").html( colorize( obj.topic ) );
				if ( obj.nickname ) {
					$("#topic").append('<br />(set by ' + obj.nickname + ')');
				}
				$("#topic").customFadeIn( "slow" );
			}
			topic = obj.topic;
			
			setTimeout( getTopic, 2500 );
		}
	);	
}

function initializeMantisTicker() {
	$.post( "/gaben_api/mantis/gaben_mantis.php", { req: 'login_status' }, function( response )
		{
			var obj = $.evalJSON( response );
			if ( obj.loggedin ) {
				$("#mantis_login").hide();
				$("#login_status").prepend( 'Logged in as ' + obj.username );
				$("#login_status").customFadeIn( "slow" );
				
				mantisGetBugs();
			} else {
				$("#bugs_updated").hide();
				$("#bugs_assigned").hide();
				$("#bugs_new").hide();
				
				$("#mantis_username").val( '' );
				$("#mantis_password").val( '' );
				$("#mantis_login").customFadeIn( "slow" );
				$("#login_status").html( ' [<a href="#" id="mantis_logout">logout</a>] | <a id="mantis_log" href="/gaben_api/mantis/gaben_mantis.php?req=log"><img align="middle" src="/img/mantis/log.png" alt="log"/></a>' );
				
				$("#mantis_logout").click( mantisLogout );
				$("#mantis_log").attr( 'href', '/gaben_api/mantis/gaben_mantis.php?req=log' );
				$("#mantis_log").fancybox( { 'hideOnContentClick': false, 'frameWidth' : 900, 'frameHeight' : 600 } );
				
				$("#mantis_username").select();
			}
			$("#mantis_ticker").customFadeIn( "slow" );
		}
	);
}

function mantisLogin() {
	$("#mantis_username").select();
	$.post( "/gaben_api/mantis/gaben_mantis.php", { req: 'login', mantis_username: $("#mantis_username").val(), mantis_password: $("#mantis_password").val() }, function( response )
		{
			var obj = $.evalJSON( response );
			$("#mantis_ticker").customFadeOut( "slow" );
			$("#mantis_error_container").customFadeOut( "slow" );
			$("#mantis_message_container").customFadeOut( "slow" );
			$("#login_status").customFadeOut( "slow" );
			setTimeout( function()
				{
					if ( obj.login_success ) {
						initializeMantisTicker();
					} else {
						$("#mantis_error").html( obj.error );
						$("#mantis_error_container").customFadeIn( "slow" );
						$("#mantis_username").select();
					}
					
					$("#mantis_ticker").customFadeIn( "slow" );
				}
				,800
			);
		}
	);
	return false;
}

function mantisLogout() {
	$.post( "/gaben_api/mantis/gaben_mantis.php", { req: 'logout' }, function( response )
		{
			var obj = $.evalJSON( response );
			if ( obj.logout_success ) {
				$("#mantis_ticker").customFadeOut( "slow" );
				$("#mantis_error_container").customFadeOut( "slow" );
				$("#mantis_message_container").customFadeOut( "slow" );
				$("#login_status").customFadeOut( "slow" );
				
				$("#bugs_updated").customFadeOut( "slow" );
				setTimeout( function()
					{
						initializeMantisTicker();
					}
					,800
				);
			}
		}
	);
}


function mantisGetBugs() {
	$("#mantis_throbber").customFadeIn( "slow" );
		
	$.post( "/gaben_api/mantis/gaben_mantis.php", { req: 'getbugs' }, function( response )
		{
			var obj = $.evalJSON( response );
			if ( obj.bugs_exist ) {
				// Recently Updated bugs
				if ( obj.bugs.updated_present ) {
					$("#bugs_updated").customFadeOut( "slow" );
					setTimeout( function()
						{
							var html = '';
				            $.each(obj.bugs.updated ,function( i, bug ) {
				            	html += '<tr><td><img src="' + bug.img + '" />&nbsp;<span onmouseover="Tip(\'' + bug.tooltip + '\', DELAY, 5)" onmouseout="UnTip()">' + bug.summary + '</span></td></tr>';
				            });
				            
				            $("#bugs_updated_body").html( html );
							$("#bugs_updated").customFadeIn( "slow" );
						}
						,800
					);					
				} else {
					$("#bugs_updated").customFadeOut( "slow" );
				}
				
				
				// Assigned to me
				if ( obj.bugs.assigned_present ) {
					$("#bugs_assigned").customFadeOut( "slow" );
					setTimeout( function()
						{
							var html = '';
							var count = 0;
				            $.each(obj.bugs.assigned ,function( i, bug ) {
				            	html += '<tr><td><img src="' + bug.img + '" />&nbsp;<span onmouseover="Tip(\'' + bug.tooltip + '\', DELAY, 5)" onmouseout="UnTip()">' + bug.summary + '</span></td></tr>';
				            	count++;
				            });
				            
				            $("#bugs_assigned_body").html( html );
							$("#bugs_assigned").customFadeIn( "slow" );
							
							/*
							var ie_breaks = '';
							for ( b = 0; b <= count + 1; b++ ) {
								ie_breaks += '<br />'
							}
							$("#iebullshit_assigned").html( ie_breaks );
							*/
						}
						,800
					);					
				} else {
					$("#bugs_assigned").customFadeOut( "slow" );
				}
				
				// New bugs
				if ( obj.bugs.new_present ) {
					$("#bugs_new").customFadeOut( "slow" );
					setTimeout( function()
						{
							var html = '';
				            $.each(obj.bugs.newbugs ,function( i, bug ) {
				            	html += '<tr><td><img src="' + bug.img + '" />&nbsp;<span onmouseover="Tip(\'' + bug.tooltip + '\', DELAY, 5)" onmouseout="UnTip()">' + bug.summary + '</span></td></tr>';
				            });
				            
				            $("#bugs_new_body").html( html );
							$("#bugs_new").customFadeIn( "slow" );
						}
						,800
					);
				} else {
					$("#bugs_new").customFadeOut( "slow" );
				}
				
				$("#mantis_message_container").customFadeIn( "slow" );
			} else {
				$("#bugs_updated").customFadeOut( "slow" );
				$("#bugs_new").customFadeOut( "slow" );
				$("#bugs_assigned").customFadeOut( "slow" );
			}
			$("#mantis_throbber").customFadeOut( "slow" );
		}
	);
}

function colorize (message) {
	var pageBack  = 'white';
	var pageFront = 'black';
	var length    = message.length;
	var newText   = '';
	var bold      = false;
	var color     = false;
	var reverse   = false;
	var underline = false;
	var foreColor = '';
	var backColor = '';
	for (var i = 0 ; i < length ; i++) {
		switch (message.charAt(i)) {
			case String.fromCharCode(2):
				if (bold) {
					newText += '</b>';
					bold     = false;
				} else {
					newText += '<b>';
					bold    = true;
				}
				break;
			case String.fromCharCode(3):
				if (color)	{
					newText += '</span>';
					color = false;
				}
				foreColor = '';
				backColor = '';
				if ((parseInt(message.charAt(i+1)) >= 0) && (parseInt(message.charAt(i+1)) <= 9)) {
					color = true;
					if ((parseInt(message.charAt(++i+1)) >= 0) && (parseInt(message.charAt(i+1)) <= 9)) {
						foreColor = getColor(parseInt(message.charAt(i)) * 10 + parseInt(message.charAt(++i)));
					} else {
						foreColor = getColor(parseInt(message.charAt(i)));
					}
					if ((message.charAt(i+1) == ',') && (parseInt(message.charAt(++i+1)) >= 0) && (parseInt(message.charAt(i+1)) <= 9)) {
						if ((parseInt(message.charAt(++i+1)) >= 0) && (parseInt(message.charAt(i+1)) <= 9)) {
							backColor = getColor(parseInt(message.charAt(i)) * 10 + parseInt(message.charAt(++i)));
						} else {
							backColor = getColor(parseInt(message.charAt(i)));
						}
					}
				}
				if (foreColor) {
					newText += '<span style="color:'+foreColor;
					if (backColor) {
						newText += ';background-color:'+backColor;
					}
					newText += '">';
				}
				break;
			case String.fromCharCode(15):
				if (bold) {
					newText += '</b>';
					bold     = false;
				}
				if (color) {
					newText += '</span>';
					color    = false;
				}
				if (reverse) {
					newText += '</span>';
					reverse  = false;
				}
				if (underline) {
					newText  += '</u>';
					underline = false;
				}
				break;
			case String.fromCharCode(22):
				if (reverse) {
					newText += '</span>';
					reverse  = false;
				} else {
					newText += '<span style="color:'+pageBack+';background-color:'+pageFront+'">';
					reverse  = true;
				}
			case String.fromCharCode(31):
				if (underline) {
					newText  += '</u>';
					underline = false;
				} else {
					newText  += '<u>';
					underline = true;
				}
			default:
				newText += message.charAt(i);
				break;
		}

	}
	if (bold)      newText += '</b>';
	if (color)     newText += '</span>';
	if (reverse)   newText += '</span>'
	if (underline) newText += '</u>';
	return newText;
}

function getColor(numeric)
{
	var num = parseInt(numeric);
	switch (num) {
		case 0:  return 'white';
		case 1:  return 'black';
		case 2:  return 'navy';
		case 3:  return 'green';
		case 4:  return 'red';
		case 5:  return 'maroon';
		case 6:  return 'purple';
		case 7:  return 'olive';
		case 8:  return 'yellow';
		case 9:  return 'lime';
		case 10: return 'teal';
		case 11: return 'aqua';
		case 12: return 'blue';
		case 13: return 'fuchsia';
		case 14: return 'gray';
		default: return 'silver';
	}
}
