var mainData = {};
var eventSubmenu = null;

mainData.logged = false;

$(function() {
	
	$('ul#menu_side li').hover(hlItem, uhlItem);
	
	if ($('div#reg_terms').attr('id')) {
		$('div#reg_terms').load(getURL.base + '/request/terms/clear/1');
	}
	
	mainData.totalUsersCountFontSize = $('b#total_users_online_count').css('font-size');
	$('#users_online').click( function () {
		$.post( getURL('request/totalusersonline'), null, updateTotalUsersOnline);
		animateTotalUsersOnline();
	});
	
	mainData.totalUsersOnlineCount = 0;
	mainData.totalUsersIID	= window.setInterval(function() {
		$.post( getURL('request/totalusersonline'), null, updateTotalUsersOnline);
	}, 30*1000);
	
	FB.init("92c4738942450ed0cbb7b023625bb957", '/xd_receiver.htm' );
	
	if ( $('div.fb_side_notice:first').attr('id') ) {
		mainData.fbSideNoticeHeight = $('div.fb_side_notice:first').height();
		$('div.fb_side_notice:first').height( 0 );
		$('div.fb_side_notice:first').hide();
	}
	
	mainData.menuCloseIID = new Array();
	mainData.hili = new Array();
	
	$ajaxLoadin = $( 'div#ajax_loading' );
	$ajaxLoadin.width_fixed = $ajaxLoadin.width();
	$ajaxLoadin.height_fixed = $ajaxLoadin.height();
	$ajaxLoadin.width( 0 );
	$ajaxLoadin.height( 0 );
	
	$( window ).bind( 'resize', null, function() {
		$( '#blocker_fullscreen' ).height( $(document).height() ).width( $(document).width() );
	});
});



function loadUserData(uid) {
	mainData.uid = uid;
	mainData.logged = true;
}

/************************************
 * Generic
 ************************************/
function getGenericFrame( str ) {
	var content = '';
	if ( str != undefined || str != null ) {
		content = str;
	}
	
	return mainData.genericFrameHeader + content + mainData.genericFrameFooter;
}

function setURL(str) {
	if (str == undefined) {
		return null;
	}
	
	getURL.base = str;
}

function getURL(url) {
	if (getURL.base == undefined && url != undefined) {
		return url;
	} else if (getURL.base != undefined && url == undefined) {
		return getURL.base + '/';
	}
	
	return getURL.base + '/' + url;
}

function getScroll() {
	if (window.scrollX != undefined) {
		posY = window.scrollY;
	} else {
		posY = document.documentElement.scrollTop;
	}
	return posY + 100;
}

function getResponse( url, params, callback ) {
	if ( params == undefined ) {
		params = null;
	}
	
	if ( callback == undefined ) {
		callback = null;
	}
	
	getResponse.callbackFunction = callback;
	
	$('#blocker_fullscreen').html( '' );
	$.post( getURL( url ) + '?prev=cache', params,
		function( data ) {
		
			if ( $.isFunction( getResponse.callbackFunction ) ) {
				if ( getResponse.callbackFunction( data ) == false ) {
					return false;
				}
			}
			
			$( '#blocker_fullscreen' ).html( getGenericFrame( data ) );
			showBlocker();
	});
}

function hlItem( ) {
	hlItem.menu_item_bg = $(this).css('background-color');
	
	if (hlItem.menu_item_bg == undefined) {
		hlItem.menu_item_bg = 'none';
	}
	
	//if ( hlItem.classType == undefined || hlItem.classType == null ) {
	
	if ( $(this).attr( 'hiliclass' ) == undefined || $(this).attr( 'hiliclass' ) == null ) {
		$(this).addClass('hili_default');
	} else {
		$(this).addClass( $(this).attr( 'hiliClass' ));
	}
}

function uhlItem() {
	if ( $(this).attr( 'hiliclass' ) == undefined || $(this).attr( 'hiliclass' ) == null ) {
		$(this).removeClass('hili_default');
	} else {
		$(this).removeClass( $(this).attr( 'hiliClass' ) );
	}
}

function showBlocker() {
	$( '#blocker_fullscreen' ).height( $(document).height() ).width( $(document).width() );
	$( '#blocker_fullscreen table.frame:first' ).css( 'margin-top', getScroll() + 'px' );
	
	$( '#blocker_fullscreen' ).css( 'opacity', 0 );
	$( '#blocker_fullscreen' ).show();
	$( '#blocker_fullscreen' ).animate( { opacity: 1 }, 350, 'swing' );
}

function hideBlocker() {
	$( '#blocker_fullscreen' ).animate( { opacity: 0 }, 350, 'swing', function() {
		$( '#blocker_fullscreen' ).hide();
	});
}

function toggleBlocker(show) {
	if ( $('#blocker_fullscreen').css( 'display' ) == 'none' ) {
		showBlocker();
	} else {
		hideBlocker();
	}
}

function ignoreUser(ident) {
	if (typeof arguments[0] == 'number') {
		params = 'uid/' + arguments[0];
	} else if (typeof arguments[0] == 'string') {
		params = 'username/' + arguments[0];
	}
	
	getResponse('request/ignore/' + params);
}

function unignoreUser(ident) {
	if (typeof arguments[0] == 'number') {
		params = 'uid/' + arguments[0];
	} else if (typeof arguments[0] == 'string') {
		params = 'username/' + arguments[0];
	}
	
	getResponse('request/unignore/' + params);
}

/************************************
 * 		Ajax related functions
 ************************************/

function showAjaxLoading() {
	$ajaxLoadin.show()
				.stop( true )
				.animate( { opacity: 1, width: $ajaxLoadin.width_fixed, height: $ajaxLoadin.height_fixed },
						500, 'swing' );
	
	window.setTimeout( function() { hideAjaxLoading(); }, 60*1000 );
}

function hideAjaxLoading() {
	$ajaxLoadin.stop( true ).animate( { opacity: 0, width: 0, height: 0 }, 500, 'linear', function() {
		$ajaxLoadin.hide();
	});
}

/************************************
 * 		Submenu functions
 ************************************/

function initSubmenu(e, menu) {
	params = '';
	
	if (e.pageX != undefined) {
		eventSubmenu = e;
	} else {
		eventSubmenu = { pageX: e.clientX + document.documentElement.scrollLeft,
						 pageY: e.clientY + document.documentElement.scrollTop };
	}
	
	if ( typeof ($submenu) === 'undefined' ) {
		$( 'body' ).append('<div id="submenu">' + getGenericFrame() + '</div>');
		$submenu = $( 'div#submenu' );
		$submenu.mouseleave(hideSubmenu);
	}
	
	params = '';
	switch (menu) {
		case 'chat':
			if (typeof arguments[3] == 'number') {
				params += 'crid/' + arguments[3] + '/';
			}
		case 'user':
			if (typeof arguments[2] == 'number') {
				params += 'uid/' + arguments[2] + '/';
			} else if (typeof arguments[2] == 'string') {
				params += 'username/' + arguments[2] + '/';
			}
			break;
		default:
			return false;
		break;
	}
	
	positionElement( 'div#ajax_loading', eventSubmenu.pageX, eventSubmenu.pageY - ($ajaxLoadin.height_fixed + 4) );
	showAjaxLoading();
	
	$submenu.stop( true )
			.css( 'width', 'auto' )
			.css( 'height', 'auto' );
	
	$( 'div#submenu td.frame_content' ).load( getURL( 'request/' + menu + 'submenu/' + params ), null, showSubmenu);
	return true;
}

function showSubmenu() {
	if ( typeof ($submenu) === 'undefined' ) {
		return;
	}
	
	e = eventSubmenu;
	
	hideAjaxLoading();
	
	positionElement( 'div#submenu', e.pageX - 10, e.pageY - 10)
	
	$submenu.width_last = $submenu.width();
	$submenu.height_last = $submenu.height();
	$submenu.width( 0 ).height( 0 );
	$submenu.stop( true )
			.show( )
			.animate( { opacity: 1, width: $submenu.width_last, height: $submenu.height_last }, 500, 'swing' );
}

function hideSubmenu() {
	if ( typeof ($submenu) === 'undefined' ) {
		return;
	}
	
	hideAjaxLoading();
	
	$submenu.stop( true )
			.animate( { opacity: 0, width: 0, height: 0 }, 500, 'swing', function() {
							$submenu.hide();
							$( 'div#submenu td#frame_content' ).html( '' );
						});
}

function positionElement( elem, offsetX, offsetY ) {
	$elem = $( elem );
	
	// NOTE use $.scroll functions?
	if (window.scrollX != undefined) {
		maxX = window.scrollX + window.outerWidth - 18;
		maxY = window.scrollY + window.innerHeight - 18;
	} else {
		maxX = document.documentElement.scrollLeft + document.documentElement.clientWidth;
		maxY = document.documentElement.scrollTop + document.documentElement.clientHeight
	}
	
	if (offsetX + $elem.width() > maxX) {
		posX = offsetX - $elem.width();
	} else {
		posX = offsetX;
	}
	
	if (offsetY + $elem.height() > maxY) {
		posY = offsetY - $elem.height();
	} else {
		posY = offsetY;
	}
	
	$elem.css('left', (posX-4) + 'px');
	$elem.css('top', (posY-4) + 'px');
	
	return;
}



/***********************************************
 *  The submenus for the main menu buttons
 ***********************************************/

function showMenu( name ) {
	if ( name == undefined || name == null ) {
		return;
	}
	
	$elem = $('div#dropdown_' + name);
	
	if ( !$elem.attr('id') ) {
		return;
	}
	
	if ( mainData.menuCloseIID[name] ) {
		window.clearTimeout( mainData.menuCloseIID[name]  );
		return;
	}
	
	for (var i = 1; $('div#dropdown_' + name + ' a#dropitem_' + i).attr( 'id' ); i++ ) {
		$item = $('div#dropdown_' + name + ' a#dropitem_' + i);
		$item.stop( true );
		
		$item.css( 'top', 0 );
		
		$item.animate( { top: ( ( $item.height()) * (i-1) ) }, 250, 'swing' );
	}
	
	$elem.css( 'visibility', 'visible' );
}

function hideMenu( name ) {
	if ( name == undefined || name == null ) {
		return;
	}
	
	$elem = $('div#dropdown_' + name);
	
	if ( !$elem.attr('id') ) {
		return;
	}
	
	
	mainData.menuCloseIID[name] = window.setTimeout( function() {
		mainData.menuCloseIID[name] = false;
		/*for (var i = 1; $('div#dropdown_' + name + ' a#dropitem_' + i).attr( 'id' ); i++ ) {
			//$('div#dropdown_' + name + ' a#dropitem_' + i).css( 'visibility', 'hidden' );
		}*/
		$('div#dropdown_' + name).css( 'visibility', 'hidden' );
	}, 250);
}

/************************************
 * 		User online widget functions
 ************************************/

function updateTotalUsersOnline(data) {
	var count = parseInt(data);
	
	if ( count != mainData.totalUsersOnlineCount ) {
		mainData.totalUsersOnlineCount = count;
		
		animateTotalUsersOnline();
	}
	
	$('b#total_users_online_count').text(mainData.totalUsersOnlineCount);
}

function animateTotalUsersOnline() {
	$('#users_online').stop(true, false);
	
	$('#users_online')
	.animate( { opacity: 0 }, 160, 'swing' )
	.animate( { opacity: 1 }, 160, 'swing' )
	.animate( { opacity: 0 }, 160, 'swing' )
	.animate( { opacity: 1 }, 160, 'swing' );
}

/***********************************************
 *	Screenshots
 ***********************************************/

function showScreenshot( path ) {
	$('#blocker_fullscreen').html( '' );
	$('#blocker_fullscreen').html( getGenericFrame( '<img src="' + path + '" alt="Screenshot" />' ) );
	$('#blocker_fullscreen img:first')
		.addClass( 'cursor_pointer' )
		.click( hideBlocker );
	
	var left = Math.round( ( $(window).width() - ( 1024 + 2*10 ) ) / 2 );
	var top = Math.round( ( $(window).height() - ( 768 + 2*20 ) ) / 2 );
	
	if ( left < 0 ) {
		left = 0;
	}
	
	if ( top < 0 ) {
		top = 0;
	}
	
	$('#blocker_fullscreen table.frame:first')
		.css( 'position', 'absolute' )
		.css( 'left', left + 'px')
		.css( 'top', (top -100) + 'px' );
	showBlocker();
}

/***********************************************
 *	Publishing and permissions.
 ***********************************************/

function fbOnlogin() {
	window.setTimeout(function() {
		window.location.href = getURL('request/fblogin');
	}, 1000);
}


/**
 * Publish to user's wall from a server side template.
 * 'welcome' for instance.
 */
function fbStreamPublishTemplate( templateName, targetname ) {
	if ( templateName == undefined ) {
		return;
	}
	
	if ( targetname == undefined ) {
		targetname = 'somebody';
	}
	
	FB.ensureInit( function() {
		if ( !FB.Connect.get_loggedInUser() ) {
			return;
		}
		
		$.post( getURL('request/fbgetstreamtemplate'), { name : templateName, target_name : targetname }, function(data) {
			if ( data == undefined ) {
				return;
			}
			
			if ( data.target_id == null || data.target_id == undefined ) {
				data.target_id = FB.Connect.get_loggedInUser();
			}
			
			fbStreamPublish( data.attachment , data.action_links, data.subject, data.prompt, data.target_id, data.actor_id);
		}, 'json');
	
	});
}

function fbStreamPublish( attachment, action_links, subject, prompt, target_id, actor_id ) {
	
	if ( subject == undefined ) {
		subject = null;
	}
	
	if ( prompt == undefined ) {
		prompt = null;
	}
	
	if ( actor_id == undefined ) {
		actor_id = null;
	}
	
	FB.ensureInit(function() {
		if ( !FB.Connect.get_loggedInUser() ) {
			return;
		}
		
		if ( target_id == undefined || target_id == null ) {
			target_id = FB.Connect.get_loggedInUser();
		}
		
		FB.Connect.streamPublish( subject, attachment, action_links, target_id, prompt, function(posd_id, exception) {
			/*if ( exception ) {
				alert( exception );
			}*/
		}, false, actor_id);
	});
}

function fbShowPermissionsDialog( perms ) {
	if ( perms == undefined ) {
		return;
	}
	
	FB.ensureInit(function() {
		if ( !FB.Connect.get_loggedInUser() ) {
			return;
		}
		
		FB.Connect.showPermissionDialog( perms, function( allowed_perms ) {
			//alert( allowed_perms );
		});
	});
}

function fbPromoteInitialPermissions(name, pw) {
	FB.ensureInit(function() {
		if ( !FB.Connect.get_loggedInUser() ) {
			return;
		}
		
		FB.Connect.showPermissionDialog( 'email, publish_stream', function( allowed_perms ) {
			
			if ( allowed_perms == undefined || allowed_perms == null
					|| allowed_perms.lenght <= 0 ) {
				fbStreamPublishTemplate( "welcome" );
				return;
			}
			
			var perms = allowed_perms.split( ',' );
			
			if ( perms[0] == 'email' || ( perms.length > 1 && perms[0] == 'email' ) ) {
				$.post( getURL('request/fbsendregnotification'), { username: name, password: pw }, function() { 
					fbStreamPublishTemplate( "welcome" );
				});
			} else {
				fbStreamPublishTemplate( "welcome" );
			}
		});
	});
}

/***********************************************
 *	Cosmetic Facebook related. 
 ***********************************************/

function fbToggleHelp(element) {
	if ( $(element).height() == 0 ) {
		$(element).show();
		$(element).animate( { height: mainData.fbSideNoticeHeight }, 500, 'swing' );
	} else if ( $(element).height() == mainData.fbSideNoticeHeight ) {
		$(element).animate( { height: 0 }, 500, 'linear', function() {
			$(element).hide();
		});
	}
}





















