
// modified from: http://sigswitch.com/2010/04/updated-textarea-maxlength-with-jquery-plugin/
// moved maxlength from html to plugin options

jQuery.fn.limitMaxlength = function(options){

	var settings = jQuery.extend({
		maxlength: 100,
		onLimit: function(){},
		onEdit: function(){}
	}, options);

	// Event handler to limit the textarea
	var onEdit = function(){
		var textarea = jQuery(this);
		var maxlength = settings.maxlength;

		if(textarea.val().length > maxlength){
			textarea.val(textarea.val().substr(0, maxlength));

			// Call the onlimit handler within the scope of the textarea
			jQuery.proxy(settings.onLimit, this)();
		}

		// Call the onEdit handler within the scope of the textarea
		jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
	}

	this.each(onEdit);

	return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit);
}

var scrolling = true;
jQuery.fn.nextTab = function() {
    if(!scrolling) return;
    var self = $(this);
	var defaults = {
  	    prev: '#prev',
    	next: '#next',
    	tabs: '#teaserTabs',
      	items: self.find('.teaseritem'),
    	speed: 1000
  	};
    var options = $.extend(defaults, options);
	var indicator = $(options.tabs).find('#indicator');

    var selected = $(options.tabs + ' a.selected');
    var oldIndex = $(options.tabs + ' a').index(selected);
    var newIndex = (oldIndex + 1) % options.items.length;

    self.find('div.teaseritem:visible').css('z-index',50).stop(true, true).fadeOut(options.speed);
    self.find('div.teaseritem:eq('+newIndex+')').css('z-index',100).stop(true, true).fadeIn(options.speed);

    var tab = $(options.tabs + ' a:eq('+newIndex+')');
    var position = tab.parent().position();
    var tabwidth = tab.parent().width();
    $(options.tabs + ' a').removeClass('active selected');
    tab.addClass('selected');
    if (position) {
    	indicator.animate({left:position.left,width:tabwidth},'easeOutSine',function(){$(options.tabs + ' a').removeClass('active');tab.addClass('active');});
    }
}

jQuery.fn.teasers = function(options){
	var self = $(this);
	var defaults = {
  	    prev: '#prev',
    	next: '#next',
    	tabs: '#teaserTabs',
      	items: self.find('.teaseritem'),
    	speed: 1000
  	};
	var options = $.extend(defaults, options);
  	var currentTeaser = 0;
	var indicator = $(options.tabs).find('#indicator');
	var numTeasers = options.items.length;
	var first = $(options.tabs +' a:first').addClass('selected');
	var prev = $(options.prev);
	var next = $(options.next);
	options.items.each(function(i){
		$(this).css({'position':'absolute','top':'0','left':'0'});
	});
  	prev.fadeIn(1000).css('z-index',150).click(function(e){
		currentTeaser = (currentTeaser == 0) ? numTeasers-1 : currentTeaser-1;
		self.changeTeaser();
		_gaq.push(['_trackEvent', 'frontpage', 'tab-select', 'prev']);
	});
	next.fadeIn(1000).css('z-index',150).click(function(e){
		currentTeaser = (currentTeaser == numTeasers-1) ? 0 : currentTeaser+1;
		self.changeTeaser();
		_gaq.push(['_trackEvent', 'frontpage', 'tab-select', 'next']);
	});

	indicator.css('width',first.parent().width()).slideDown('easeOutSine',function(){first.addClass('active')});

	$(options.tabs + ' a').click(function(e){
		e.preventDefault();
		var index = $(options.tabs + ' a').index(this);

		//if(currentTeaser == index){return false;}
		currentTeaser = index;
		self.changeTeaser();
		_gaq.push(['_trackEvent', 'frontpage', 'tab-select', currentTeaser]);
	});

  	self.changeTeaser = function(){
		self.find('div.teaseritem:visible').css('z-index',50).stop(true, true).fadeOut(options.speed);
		self.find('div.teaseritem:eq('+currentTeaser+')').css('z-index',100).stop(true, true).fadeIn(options.speed);

		var tab = $(options.tabs + ' a:eq('+currentTeaser+')');
		var position = tab.parent().position();
		var tabwidth = tab.parent().width();
		$(options.tabs + ' a').removeClass('active selected');
        tab.addClass('selected');
		indicator.animate({left:position.left,width:tabwidth},'easeOutSine',function(){$(options.tabs + ' a').removeClass('active');tab.addClass('active');});

        scrolling = false;
   	}

}

$('document').ready(function(){
	$('#langHolder').load('files/languages.php');

	$('.tabs').tabs();

	var $loginTabs = $('#loginFormContainer').tabs({
		select: function(event, ui){
			if (_gaq){
				_gaq.push(['_trackPageview',(ui.index == 0 ? '/signup/':'/login/')]);
			}
		}
	});
	var roomTabs = $('#roomTabs').tabs();
	roomTabs.tabs('select', 0);

	// link_sign_up
	$('.login, .opensignup').fancybox({
		'scrolling'		: 'no',
		'autoDimensions': false,
		'width'			: 770,
		'height'		: 430,
		'overlayOpacity': '0.8',
		'overlayColor'	: '#000',
		'padding'		: 15,
		'titleShow'		: false
	}).click(function() {
	    $loginTabs.tabs('select', 1);
		$('#login_email').focus();
    	return false;
	});

	//link_sign_in
	$('a#pokerRoomDownload, .join, .openregistration').fancybox({
		'scrolling'		: 'no',
		'autoDimensions': false,
		'width'			: 770,
		'height'		: 430,
		'overlayOpacity': '0.8',
		'overlayColor'	: '#000',
		'padding'		: 15,
		'titleShow'		: false
	}).click(function() {
	    $loginTabs.tabs('select', 0);
		$('#email').focus();
    	return false;
	});;

//	$('#tabJoin').click(function() { $('#login_email').focus(); });
//	$('#tabRegister').click(function() { $('#email').focus(); });

	//registration form
	var originalMessage = $('#registerForm').find('.message > span').text();
	$("#registerForm").bind("submit", function() {
		var emptycount = $(this).find('.required[value!=""]').length;
		var required = $(this).find('.required').length;
		if(emptycount != required){
			$(this).find('.message').slideDown();
			$(this).find('.message > span').text(originalMessage);
			$(this).find('.required').each(function(i){
				if($(this).val() < 1){
					$(this).parent().addClass('is_empty');
				}
				else{
					$(this).parent().removeClass('is_empty');
				}
			});
		}
		else{
			$(this).find('.message').slideUp();
			$(this).find('label').removeClass('is_empty');

			// clientside validation pass, do a ajax request to the server and get response
			$.fancybox.showActivity();
			$.ajax({
				url: 		'/register/new/',
				type:		'get',
				dataType: 	'json',
				data: 		$(this).serializeArray(),
				success: 	function(data, status, req) {
					$.fancybox.hideActivity();
					var form = $('#registerForm');
					if(data.status == 'ok') {
						form.find('.message > span').text(data.message).parent().slideDown();
						// account created. reload the page.
						// window.roomRedirect && window.roomRedirectTitle
						var redir = window.roomRedirect ? window.roomRedirect : '';
						if(redir != '') {
							// set a small delay to give user chance to see the thank you message.
							var cmd = 'window.location.replace(\'' + redir + '\')';
							setTimeout(cmd, 2000);
						}
						else {
							// no redirect, just reload.
							setTimeout('location.reload()', 2000);
						}
					} else {
						form.find('.message > span').text(data.message).parent().slideDown();
						var emptyfields = '#'+ data.fields.join(',#')
						$(emptyfields).parent().addClass('is_empty');
					}
				}
			});
		}
		return false;
	});

	//login form
	$("#loginForm").bind("submit", function() {
		$(this).find('.message').slideUp();
		$.fancybox.showActivity();
		$.ajax({
			url:		'/login/dologin/',
			type:		'post',
			dataType:	'json',
			data:		$(this).serializeArray(),
			success:	function(data) {
				$.fancybox.hideActivity();
				var form = $('#loginForm');
				if(data.status == 'ok') {
					// account created. reload the page.
					// window.roomRedirect && window.roomRedirectTitle
					var redir = window.roomRedirect ? window.roomRedirect : '';
					if(redir != '') {
						window.location.replace(redir);
					}
					else {
						// no redirect, just reload.
						location.reload();
					}
				} else {
					form.find('.message > span').text(data.message).parent().slideDown();
					var emptyfields = '#'+ data.fields.join(',#')
					$(emptyfields).parent().addClass('is_empty');
				}
			}
		});

		return false;
	});

	$('.subscribe').bind('submit', function() {
		$.fancybox.showActivity();
		$.ajax({
			url:		'subscribe/',
			type:		'post',
			dataType:	'json',
			data:		$(this).serializeArray(),
			success:	function(data)
			{
				if(data.status == 'ok')
				{
					$('.subscribe').html('<h3>Thank you</h3><p>' + data.message + '</p>');
				}
				else
				{
					alert(data.message);
				}
				$.fancybox.hideActivity();

			}
		});
		return false;
	});


	//add room

	$('.addRoom').fancybox({
		'scrolling'		: 'no',
		'overlayOpacity': '0.8',
		'overlayColor'	: '#000',
		'padding'		: 30,
		'titleShow'		: false
	});

	window.originalTitle = $('#login-redirect-1').html();
	if(window.roomRedirect && window.roomRedirectTitle && $('#login-redirect-1').length > 0)
	{
		$('#login-redirect-1,#login-redirect-2').html($('#login-redirect-1').html().replace('{ROOM}', window.roomRedirectTitle));
		$('#login-redirect-1,#login-redirect-2').attr('href', window.roomRedirect);
	}
	else
	{
		$('#login-redirect-1,#login-redirect-2').hide();
	}

	$("#addPokerRoom").bind("submit", function() {});

	numTeasers = $('#teaser .teaseritem').length;
	$('#teaser').teasers();
    setInterval('$(\'#teaser\').nextTab();', 10000);

	$('#newsletter_email, .newsletter_email').focus(function(){$(this).attr('value','')});

	var onEditCallback = function(remaining){
		$(this).siblings('.charCounter').text(remaining + " characters left");

		if(remaining > 0){
		}
	}

	var onLimitCallback = function(){
	}

	$('#comment textarea').limitMaxlength({
		maxlength : 1200,
		onEdit: onEditCallback,
		onLimit: onLimitCallback
	});

	$('form .no-history').attr('autocomplete','off');
	$('.fb_loginbtn').click(function(){
		FB.getLoginStatus(function(resp) {
			if(resp.session) {
				location.replace('/poker-forum/?dofbredirect=1');
			}
			else{
				FB.login(function(response){
					location.replace('/poker-forum/?dofbredirect=1');
				});
			}
		});
	});

});

	function resetRedirect(url, title)
	{
		if($('#login-redirect-1').length == 0) return; // exit if the login html is not included in the page

		window.roomRedirect = url;
		window.roomRedirectTitle = title;

		if(window.roomRedirect && window.roomRedirectTitle)
		{
			$('#login-redirect-1,#login-redirect-2').show();
			$('#login-redirect-1,#login-redirect-2').html(window.originalTitle.replace('{ROOM}', window.roomRedirectTitle));
			$('#login-redirect-1,#login-redirect-2').attr('href', window.roomRedirect);
		}
		else
		{
			$('#login-redirect-1,#login-redirect-2').hide();
		}
	}

//RAF
$(function(){
	$("#refer_banners .tab_handles_ul a").click(function(){
		// select first radio
		$("input[type=radio]",$($(this).attr("href"))).first().click().change();
	});

	$("#refer_banners input[type=radio]").change(function(){
		var banner_path = $(this).val();
		var code = '<a href="http://www.rakeback.com/?referrerid='+window.rb_userid+'"><img src="'+banner_path+'" /></a>';
		$("#raf_banner_code").val(code);
	});

	$("#raf_banner_code").focus(function(){
		$(this).select();
	});

	if ($("#raf_banner_copy").length > 0 && (typeof  ZeroClipboard != "undefined")){
		window.zeroclip = new ZeroClipboard.Client();

        zeroclip.setText( '' ); // will be set later on mouseDown
        zeroclip.setHandCursor( true );
    	zeroclip.setCSSEffects( true );

    	zeroclip.addEventListener( 'mouseDown', function(client) {
			zeroclip.setText( $("#raf_banner_code").val() );
			alert("Code copied to your clipboard");
		});
		zeroclip.glue("raf_banner_copy");
	}

	// copy to clipboard
	$("#raf_banner_copy").click(function(){
		return false;
	});

	$(window).resize(function(){
		if (window.zeroclip){
			window.zeroclip.reposition();
		}
	});

	$(".tab_handles_ul").each(function(idx, ele){
		var handles = $("a[href*=#]", ele);
		handles.each(function(idx, anchor){
			$(anchor).attr("href", /#.*$/.exec($(anchor).attr("href"))[0]);
			// hide all tabs first
			$($(anchor).attr("href")).hide().find(".pe_only").hide();
		}).click(function(){
			$($("li.active", $(this).closest(".tab_handles_ul")).removeClass("active").find("a[href^=#]").attr("href")).hide();

			$(this).closest("li").addClass("active");
			var targetHref = $(this).attr("href");
			$(targetHref).show();

			if (window.zeroclip){
				window.zeroclip.reposition();
			}

			return false;
		}).first().click();
	});

	if (window.location.hash){ // deep linking!
		$(".tab_handles_ul a[href="+window.location.hash+"]").click();
	}

	$(".box_header .zoom").fancybox({scrolling: "no", titleShow: false});

	$("#invite_by_facebook").click(function(){
		var obj = {
			method: 'feed',
			name: 'Rakeback',
			link: 'http://www.rakeback.com/?referrerid='+window.rb_userid,
			picture: 'http://'+location.host+'/images/raf/rakeback_logo.jpg?v=2',
			//caption: '&nbsp;',
			description: 'Rakeback is the online poker equivalent of a loyalty program or frequent flier miles – the more you play, the more you are rewarded with real cash paid directly into your poker account every week – win or lose. Find out now how you can start earning hundreds of dollars just by playing the game you love!',
			message: 'Did you know you can get up to 40% cashback at the world’s biggest online poker sites?'
		};

		FB.ui(obj);

/*		FB.login(function(response) {
		  if (response.session) {
			if (response.scope) {
			  FB.ui(
);
			}
		  }
		}, {perms:'publish_stream'});*/
		return false;
	});


	$(".screenshot_thumb").bind("mouseover", function(){
		var target = $("#screenshot_place");
		target.attr("old_src",target.attr("src"));
		target.attr("src", $("img", this).attr("src").replace(/\.png/,"_large.png"));
	}).bind("mouseout", function(){
		var target = $("#screenshot_place");
		target.attr("src", target.attr("old_src"));
	}).bind("click", function(){
		return false;
	});
});

$(document).ready(function() {
    $('.ps-clear-redirect').click(function(){
        resetRedirect('', '');
    });

    $('#ps-confirm-button').click(function(){
        username = $('#ps-room-username').val();
        fullname = $('#ps-room-full-name').val();
        email = $('#ps-room-email').val();
        $('#ps-formcontent').load('/vip/confirm-pokerstars/?username=' +
            escape(username) + '&email=' + escape(email) + '&fullname=' +
            escape(fullname));
    });
});

$(document).ready(function() {
	var flash_obj = $('#raf_flash');
	if (flash_obj.flash){
	    flash_obj.flash({swf:'/images/raf/raf_300_200.swf',width:300,height:200});
	}
	if ($('.slideshow').length > 0) {
		$('.slideshow').slideshow();
	}
});

var rbq = rbq || [];
jQuery.each(rbq, function(idx, func){
	func();
});

$(function(){
    if (document.location.hash && document.location.hash != "#loginFormContainer"){
        $("a[href$='"+document.location.hash+"']").click();
    }
});

