/* SIO - Main Javascript
=============================================================================================*/
var SIO = {};

SIO.globals = {};

/* Onload ============================== */

$(document).ready( function()
{
	$('.hide').hide();
   $('.show').show();
	
	$('body').supersleight({shim: '/assets/images/pixel.gif'});
	
	$('.login-btn').click( function(){ SIO.overlay.load_window( $('#main'), $('#loginbox') ); return false; } );
	$('.forgetpassword-btn').click( function(){ SIO.overlay.load_window( $('#main'), $('#forgetpasswordbox') ); return false; } );
	$('.path-btn').click( function(){ SIO.overlay.load_ajax( $('#main'), '/ajax/path_selection' ); return false; } );
	
	SIO.dropdown.init( 'dropdown' );
	SIO.dropdown.admin( 'selectdropdown' );
	SIO.thumbnails.init();
	new SIO.buttons();

	if(typeof sIFR == "function"){
		
		sIFR.replaceElement("div", named({
		sSelector:".sifr", 
		sWmode: 'transparent', 
		sFlashSrc:"/assets/fonts/sifr_avantgarde.swf", 
		sColor:"#ffffff", 
		nPaddingTop:0, 
		nPaddingBottom:0
		}));
	}
	
	$('.tip').tooltip({ track: true, delay: 0, showURL: false, fade: 200 });
	
});

SIO.dropdown = 
{
	init: function( theclass )
	{
		$('.'+theclass+' .current').mouseover( 
			function(){ $(this).next().slideDown('fast'); }
		);
		
		$('.'+theclass).hover( 
			function(){},
			function(){ $(this).find('.options').slideUp('fast'); }
		);
		
		$('.'+theclass+' .current').text( $('.'+theclass+' .default').text() );
	},
	
	admin: function( theclass )
	{
		$('.'+theclass+' .current').text( $('.'+theclass+' .default').text() );
		
		$('.'+theclass).change( function()
		{
			window.location.href = $('.'+theclass+' option:selected').attr('value');
		});
	}
}

SIO.messages =
{
	init: function()
	{
		$('.cleantable .cleantableinside a').click( function()
		{
			var message_id = $(this).parent().parent().parent().parent().parent().parent().find('.messageid').text();
			SIO.messages.markread( message_id, this );
			return false;
		});
	},
	
	markread: function( message_id, that )
	{
		var icon_elm = $(that).parent().parent().find('.icon');
		
		if( icon_elm.hasClass('read') ) 
		{
			if( $(that).attr('href') != '#' ) window.location = $(that).attr('href'); 
			return false;
		}
		
		if( icon_elm.hasClass('icon') )
		{
			if( icon_elm.hasClass('unread') )
			{
				icon_elm.addClass('read').removeClass('unread');
			} 
		}
		
		$.ajax({
			type: "POST",
			url: "/users/messagemarkasread",
			data: "message_id="+message_id,
			success: function(){ 
			
				var count = $($('.messagecount')[0]).text();
				var newcount = count - 1;
				
				if( newcount >= 0 )
				{
					$('.messagecount').text(newcount);
				}
				
				var href = $(that).attr('href');
				if( href != '#' ) window.location = href; 
			}
		});
	}
	
}

SIO.tabloid = 
{
	launch: function( headline_sent_id, redirect )
	{
		SIO.overlay.load_ajax( $('#main'), '/ajax/rewardbox/' + headline_sent_id +'?redirect='+redirect, false );
		return false;
	}
}

SIO.faq = 
{
	init: function()
	{
		$('.faqlist .whitelink .question').toggle( function()
		{	
			$(this).parent().find('.answer').slideDown('fast');
			return false;													  
		},
		function()
		{	
			$(this).parent().find('.answer').slideUp('fast');
			return false;													  
		}
		);
	}
}

SIO.predictions = 
{
	init: function()
	{
		$('.placebet-btn').click( function()
		{
			$('.placebet-form').hide();
			$('.placebet-btn').show().css('display', 'block');
			$('.placebet-data').show();
			
			$(this).hide().next().show().prev().prev().hide();
			return false; 
		});
		
		$('.placebet-cancel').click( function()
		{
			$('.placebet-form').hide();
			$('.placebet-btn').show();
			$('.placebet-data').show();
			return false;
		});
	}
}

SIO.topnav =
{
	timeout: null,
	init: function()
	{
		SIO.topnav.current( true );
		
		$('#navigation .links a').each(
			function( key, elm )
			{
				var class_name = $(elm).attr('class');
				class_name = class_name.split(" ");
				
				var pos_left = $(elm).position().left+20;
				var width = $(elm).width()+8;
				
				$('#navigation .mouseover .'+class_name[0]).width(width).css({"left":pos_left});
			}
		);

		$('#navigation .links a').mouseover( function()
		{
			var class_name = $(this).attr('class');
			class_name = class_name.split(" ");
			
			$('#navigation .mouseover a').hide();
			
			if( $.browser.msie )
				$('#navigation .mouseover .'+class_name[0]).show();
			else
				$('#navigation .mouseover .'+class_name[0]).fadeIn('fast');
			
			window.clearTimeout(SIO.topnav.timeout);
		});
		
		$('#navigation .mouseover a').hover( function(){}, function()
		{ 
			SIO.topnav.current();
			
			if( $.browser.msie )
				$(this).hide();
			else
				$(this).fadeOut('fast');
		});
		
		if( $.browser.msie )
      {
			$('#navigation .links a, #navigation .mouseover a').click( 
			function(){
				
				window.location = $(this).attr('href');
				
			} );
		}
				
	},
	
	current: function( skip )
	{
		var bodyid = $('body').attr('id');
		
		if( bodyid == 'profilehome' ) 
		{
			var current = $('#profilehome #navigation .mouseover .profile');
		}
		else
		{
			var current = $('#'+bodyid+' #navigation .mouseover .'+bodyid);	
		}
		
		if( skip )
		{
			current.show();
		}
		else
		{
			if( $.browser.msie )
				current.show();
			else
				SIO.topnav.timeout = window.setTimeout( function(){ current.fadeIn('fast'); }, 300);
		}
	},
	
	update_glitz: function( value )
	{
		if( value != '')
		$('#userglitz').text(value);
	}
}

SIO.thumbnails = 
{
	init: function()
	{
		$('.thumblist .thumb .hitarea, .thumblist .thumb .info').mouseover( 
		function()
		{
			if( $(this).parent().hasClass('results') )return false;
			if( $.browser.msie && ($.browser.version <= 6) )return false;
			
			var hovercover = $(this).parent().find('.hovercover');
			var position = $(this).parent().position();
			var start_width = 132;
			var end_width = 294;
			
			$('.thumbinfo .insides').hide();
			
			$(this).parent().find('.data').children().each( function( key, elm )
			{ 
				if($(elm).text() == 'none')
					$('.thumbinfo .'+$(elm).attr('class') ).parent().hide(); 
				else
					$('.thumbinfo .'+$(elm).attr('class')).text($(elm).text()).parent().show(); 
			});
			
			$('.thumbinfo .hitarea').attr( 'href', $(this).attr('href') );
			
			if( $(this).parent().hasClass('leftside') )
			{
				$('.thumbinfo').addClass('leftinfo');
				$('.thumbinfo').css({ 'top': position.top+2, 'right': 2, 'left': 'auto' }).show().width( start_width ).animate( { width: end_width+'px' }, 100, function(){ $('.thumbinfo .insides').fadeIn( 'fast' ); });
			}
			else
			{
				$('.thumbinfo').removeClass('leftinfo');
				$('.thumbinfo').css({ 'top': position.top+2, 'left': position.left+2 }).show().width( start_width ).animate( {  width: end_width+'px' }, 100, function(){ $('.thumbinfo .insides').fadeIn( 'fast' ); });
			}
			
			hovercover.css({'opacity':0}).show().fadeTo( 'normal', 0.50 );
			
			$('.quebtn').css('z-index','17');
			$(this).parent().find('.quebtn').css('z-index','19');
		});
		
		$('.thumbinfo .hitarea').mouseout( function(){ SIO.thumbnails.hideall(); });
		$('.thumbinfo .insides').mouseover( function() { SIO.thumbnails.hideall(); });
		
		SIO.que.init();
	},
	
	hideall: function()
	{
		$('.thumbinfo').hide();
		$('.hovercover').fadeOut( 'fast' );
		$('.insides').hide();
	}
}

SIO.que = 
{
	init: function()
	{
		$('.quebtn').mouseout( function(){ SIO.thumbnails.hideall(); } ).mouseover( function(){ SIO.thumbnails.hideall(); });
		
		$('.quebtnoff').click( function()
		{
			if( !$(this).hasClass('quebtnon') )
			{
				SIO.que.add( this );
			}
			else
			{
				SIO.que.remove( this );
			}
			
			return false;
		});
		
		$('.quebtnon').click( function()
		{
			if( !$(this).hasClass('quebtnon') )
			{
				SIO.que.add( this );
			}
			else
			{
				SIO.que.remove( this );
			}
			
			return false;
		});
	},
	
	add: function( that )
	{
		$.ajax({
			type: "POST", 
			async: false, 
			dataType: "json", 
			url: $(that).attr('href'), 
			success: function( response )
			{
				if( response.error )
				{
					SIO.feedback.summon(response.error);
				}
				else
				{
					SIO.feedback.summon(response.success);
					$(that).hide();
					$(that).next().show();
				}
			}
		});
		
		return false;
	},
	
	remove: function( that )
	{
		$.ajax({
			type: "POST", 
			async: false, 
			dataType: "json", 
			url: $(that).attr('href'), 
			success: function( response )
			{
				if( response.error )
				{
					SIO.feedback.summon(response.error);
				}
				else
				{
					SIO.feedback.summon(response.success);
					$(that).hide();
					$(that).prev().show();
				}
			}
		});
		
		return false;
	},
	
	remove_profile: function( that )
	{
		$.ajax({
			type: "POST", 
			async: false, 
			dataType: "json", 
			url: $(that).attr('href'), 
			success: function( response )
			{
				if( response.error )
				{
					SIO.feedback.summon(response.error);
				}
				else
				{
					SIO.feedback.summon(response.success);
					$(that).parent().parent().parent().parent().parent().parent().parent().next(".spacer").remove();
					$(that).parent().parent().parent().parent().parent().parent().parent().remove();
				}
			}
		});
		
		return false;
	}
	
}

SIO.searchbox = 
{
	init: function( current_search )
	{
		var default_string = 'search';
		var bodyid = $('body').attr('id');
		var default_page = false;
		
		if( current_search )
		{
			$('#searchbox').val( 'search: '+current_search );
			default_string = 'search: '+current_search;
		}
		
		if( bodyid == 'users' ) default_page = 'players';
		if( bodyid == 'groups' ) default_page = 'fan clubs';
		if( bodyid == 'leaderboard' ) default_page = 'players';
		
		if( default_page )
		{
			$('.searchdown .current').text( default_page );
			$('#searchtype').val( default_page );
		}
		
		$('#searchbox').width( ($('#search .searchbar').width()-$('#search .searchdown').width())-50 );
		
		$('#search .button').click( function(){ $('#search form').submit(); return false; } );
		
		$('.searchdown .options a').click( function()
		{
			$('.searchdown .current').text( $(this).text() );
			$('.searchdown .options').slideUp('fast');
			$('#searchtype').val( $(this).text() );
			return false;
		});
		
		$('#search form').submit(function()
		{
			var value = $('#searchbox').val();
			
			if( value == '' || value == default_string )
			{	
				SIO.feedback.summon('You can\'t search for blank!');
				return false;
			}
		});
		
		$('#searchbox').focus( function()
		{
			if( $('#searchbox').val() == default_string )
			{
				$('#searchbox').val('').removeClass('mute');
			}
		}
		).blur( function()
		{
			if( $('#searchbox').val() == '' )
			{
				$('#searchbox').val(default_string).addClass('mute');
			}
		});
		
	}
}


SIO.buttons = function( active, filter )
{
   var that = this;
   active = active||false;
   filter = filter||"img, input:image";
   
   $(filter).each(function(i, val)
   {
      if( $(val).attr('src').match(/_u/) != null )
      {
         $('<img>').attr( 'src', that.over( $(val).attr('src') ) );
         
         $(val).hover (
            function() { $(this).attr( 'src', that.over($(this).attr('src')) ); },
            function() { $(this).attr( 'src', that.reset($(this).attr('src')) ); }
         );
         
         if( active )
         {
            $('<img>').attr( 'src', that.active( $(val).attr('src') ) );
            
            $(val).mousedown (
               function() { $(this).attr( 'src', that.active($(this).attr('src')) ); }
            ).mouseup (
               function() { $(this).attr( 'src', that.over($(this).attr('src')) ); }
            );
         }
      }
   });
};

SIO.buttons.prototype =
{
   over:   function( src ) { return src.replace(/(_a\.|_u\.)/, '_o.'); },
   active: function( src ) { return src.replace(/(_o\.|_u\.)/, '_a.'); },
   reset:  function( src ) { return src.replace(/(_o\.|_a\.)/, '_u.'); }
};

SIO.rating = 
{
	init: function( baseurl, quizid )
	{
		$('.results .rating .star').click( function()
		{
			var rating = $(".rating .links .star").index(this)+1;
			var that = this;
			
			$.ajax({
			  type: "POST",
			  url: baseurl+"quizzes/set_rating",
			  data: { rating: rating, quizid: quizid },
			  dataType: "json",
			  success: function( response )
			  { 
			  		if( response.error )
					{
						SIO.feedback.summon( response.error );
					}
					else
					{
						SIO.feedback.summon('Thanks for your rating!');
						var title = $(that).parent().parent().parent().find('.title');
						$(title).text( response.success );
						$('.results .rating .star').remove();
						$('.results .rating .score').removeClass('value1').removeClass('value2').removeClass('value3').removeClass('value4').removeClass('value5').addClass('value'+response.rating);
					}
			  }
			});
			
			return false;
		});
		
		$('.results .rating .star').mouseover( function()
		{ 
			var index = $(".results .rating .links .star").index(this);
			
			$('.results .rating .links .star').each( function( key, elm )
			{
				if( key <= index )
				{
					$(elm).addClass('on');
				}
				else
				{
					$(elm).removeClass('on');	
				}
			});
															
		});
		
		$('.results .rating').mouseout( function(){ $('.results .rating .links .star').removeClass('on'); } );
	}
}


SIO.login = 
{
   init: function( that )
   {
		var data = $(that).serialize();
		var done = false;
		
		$('#loginbox .submitbtn').hide();
		$('#loginbox .loadingbtn').show();
		
		$.ajax({
			type: "POST", async: false, dataType: "json", url: "/services/login", data: data+'&ajax=1',
			success: function( result )
			{
				done = true;
				
				if( result != 1 )
				{
					$('#loginbox .errorbox').show();
					
					$.each(result.errors, function( i, val ) 
					{
						$("#" + i).parent().addClass('fail').change( function(){ $(this).removeClass('fail'); } );
					});					
					
					done = false;
				}
				else
				{
					$('#registerbox .errorbox').hide();
				}
				
				SIO.overlay.jig();
				
				if( done == false )
				{
					$('#loginbox .submitbtn').show();
					$('#loginbox .loadingbtn').hide();
				}
			}
		});
		
		return done;
   }
}

SIO.register = 
{	
   init: function( that )
   {
		var data = $(that).serialize();
		var done = false;
		
		$('#registerbox .submitbtn').hide();
		$('#registerbox .loadingbtn').show();
		
		$('#registerbox .fail').parent().removeClass('fail');
		$('#registerbox .terms-fail').removeClass('terms-fail');
		
		$.ajax({
			type: "POST", async: false, dataType: "json", url: "/services/register", data: data+'&ajax=1',
			success: function( result )
			{
				done = true;
				
				if( result != '1' )
				{
					$('#registerbox .errorbox').show();
					$('#registerbox .errors').empty();
					
					$.each(result.errors, function( i, val ) 
					{
						if( i == 'ragreeterms' )
						{
							$("#" + i).change( function(){ $(this).parent().removeClass('terms-fail').removeAttr('title').unbind('mouseover'); } ).parent().addClass('terms-fail').attr('title', val[0] );
						}
						else if( i == 'rbdaymonth' || i == 'rbdayday' || i == 'rbdayyear' )
						{
							$("#" + i).addClass('select-fail').change( function(){ $(this).removeClass('select-fail').parent().removeAttr('title').unbind('mouseover'); } ).parent().attr('title', val[0] );
						}
						else
						{
							$("#" + i).parent().addClass('fail').change( function(){ $(this).removeClass('fail').parent().removeAttr('title').unbind('mouseover'); } ).parent().attr('title', val[0] );
						}
					});
					
					$('#registerbox .item').tooltip({ track: true, delay: 0, showURL: false, fade: 200 });
					
					done = false;
				}
				else
				{
					$('#registerbox .errorbox').hide();
				}
				
				SIO.overlay.jig();
				
				if( done == false )
				{
					$('#registerbox .submitbtn').show();
					$('#registerbox .loadingbtn').hide();
				}
			}
		});
		
		return done;
   }
}

SIO.forgotpass = 
{
   init: function( that )
   {
		var data = $(that).serialize();
		
		$('#forgetpasswordbox .submitbtn').hide();
		$('#forgetpasswordbox .loadingbtn').show();
		
		$.ajax({
			type: "POST", async: false, dataType: "json", url: "/services/forgotpassword", data: data+'&ajax=1',
			success: function( result )
			{
				done = true;
				
				if( result != 1 )
				{
					$('#forgetpasswordbox .errorbox').show();
					
					$.each(result.errors, function( i, val ) 
					{
						$("#" + i).parent().addClass('fail').change( function(){ $(this).parent().removeClass('fail'); } );
					});
					
					$('#forgetpasswordbox .submitbtn').show();
					$('#forgetpasswordbox .loadingbtn').hide();
					
					done = false;
				}
				else
				{
					$('#forgotstart').hide();
					$('#forgetpasswordbox .errorbox').hide();
					$('#forgetpasswordbox .successbox').show();
					$('#forgetpasswordbox .loadingbtn').hide();
				}
				
				SIO.overlay.jig();
				
				if( done == false )
				{
					$('#forgetpasswordbox .submitbtn').show();
					$('#forgetpasswordbox .loadingbtn').hide();
				}
			}
		});
		
		return false;
   }
}

SIO.profile = 
{
	edit: function( that )
	{
		$('#profile-display').hide();
		$('#profile-edit').show();
		return false;
	},
	
	noedit: function( that )
	{
		$('#profile-display').show();
		$('#profile-edit').hide();
		return false;
	}
}

SIO.comment = 
{
	leave: function( that )
	{
		$('#addcomment').hide();
		$('#commentform').show();
		
		return false;
	},
	
	cancel: function( that )
	{
		$('#addcomment').show();
		$('#commentform').hide();
		
		return false;
	},
	
	replycancel: function( i )
	{
		form = '#replyform-' + i;
		$('#addcomment').show();
		$(form).hide();
		
		return false;
	},
	
	reply: function( i )
	{
		form = '#replyform-' + i;
		$('#addcomment').hide();
		$(form).show();
		
		return false;
	}
}

SIO.accordion = 
{
	init: function()
	{
		SIO.accordion.addevent();
		
		$('.accordion:first').addClass('current');
		$('.accordion .conbox:first').show();
		
		$('.accordion .titlebar:first').unbind('click');
	},
	
	move: function( that )
	{
		$('.accordion').removeClass('current');
		
		$('.conbox').slideUp('fast');
		
		$(that).parent().addClass('current').find('.conbox').slideDown('fast');
		
		SIO.accordion.addevent();
		$(that).unbind('click');
	},
	
	addevent: function()
	{
		$('.accordion .titlebar').click( function(){ SIO.accordion.move(this); return false; } );
	}
};


SIO.admin = 
{	
   user_save: function( that )
   {
		var data = $(that).serialize();
		var done = false;
		
		$('#admin_user_edit .fail').parent().removeClass('fail');
		
		$.ajax({
			type: "POST", async: false, dataType: "json", url: "/admin/admin_user_save", data: data+'&ajax=1',
			success: function( result )
			{
				done = true;
				
				if( result != '1' )
				{
					$('#admin_user_edit .errorbox').show();
					$('#admin_user_edit .errors').empty();
					
					$.each(result.errors, function( i, val ) 
					{
						$("#" + i).parent().addClass('fail').change( function(){ $(this).removeClass('fail').parent().removeAttr('title').unbind('mouseover'); } ).parent().attr('title', val[0] );
					});
					
					$('#admin_user_edit .item').tooltip({ track: true, delay: 0, showURL: false, fade: 200 });
					
					done = false;
				}
				else
				{
					$('#admin_user_edit .errorbox').hide();
				}
				
				SIO.overlay.jig();
				
				if( done == false )
				{
					$('#admin_user_edit .submitbtn').show();
					$('#admin_user_edit .loadingbtn').hide();
				}
			}
		});
		
		return done;
   }
};


/* Messenger Service 
SIO.feedback.summon( 'the text', 'class' );
=========================================== */

SIO.feedback = {
   
   height: 100,
   
   show: function()
   {
      this.anim_in();
      this.set_timer();
   },
   
   hide: function()
   {
      window.clearTimeout(this.timer); delete this.timer;
      this.anim_out( function(){ 		
         $('#feedback .text').text( '' );
         SIO.feedback.kill_class();
         $('#feedback').css( 'display', 'none' );
      } );
   },
   
   summon: function( text, type )
   {
		type = type || '';
      SIO.feedback.kill_class();
      $('#feedback').removeClass();
      $('#feedback').addClass(type);
      $('#feedback .text').html( text );
      this.show();
   },
   
	set_timer: function()
	{
		if( typeof this.timer == "number" ) { window.clearTimeout(this.timer); delete this.timer; }
      var time = ($('#feedback .text').text().length * 100);
      if( time < 10000 ) time = 10000;
      this.timer = window.setTimeout( function(){ SIO.feedback.hide() }, time );
	},
	
   anim_in: function()
   {
		$('#feedback').css( { 'bottom': '-'+this.height+'px' } );
		
      if( $.browser.msie && ($.browser.version <= 6) )
      {
         $('#feedback').show();
         $('#feedback').css( 'opacity', 0 );
         $('#feedback').animate( { opacity: 1 }, 'fast' ); 
      }
      else
      {
         $('#feedback').show().animate( { bottom: '0px' }, 'fast' ); 
      }
   },
   
   anim_out: function( complete )
   {
      complete = complete || function(){ $('#feedback').css( 'display', 'none' ); };
      
      if( $.browser.msie && ($.browser.version <= 6) )
      {
         $('#feedback').animate( { opacity: 0 }, 'normal', function(){ $('#feedback').hide() } ); 
      }
      else
      {
         $('#feedback').animate( { bottom: '-'+SIO.feedback.height+'px' }, 'normal', complete );
      }
   },
   
   kill_class: function( complete )
   {
      $('#feedback').removeClass('general');
      $('#feedback').removeClass('error');
      $('#feedback').removeClass('credits'); 
   }
};