// For replacing images
$.fn.image = function(src, f){
    return this.each(function(){ 
        var i = new Image();
        i.src = src;
        i.onload = f;
        this.appendChild(i);
    });
}

$(document).ready(function()
{
	TopListInfoBox.init();
	ExclOffers.init();
	Spotlight.init();
	ToolTip.init();
	Screenshots.init();
	ReviewCurrencies.init();
	ReviewPayments.init();
	FakeLogoLink.init();
	ConvTest.init();
});

var TopListInfoBox = {
	init: function() {
		$('div.slots-tournament td.c-info').each(function() {
			info = $('span', this).text();
			$(this).append('<img src="/images/info.gif" class="tooltip" title="' +info +'" alt="Info" />');
		});
	}
};

var FakeLogoLink =
{
	init:function()
	{
		var $mod_prog_jackpot = $('#mod-prog-jackpot');

		if (!$mod_prog_jackpot.size())
		{
			return false;
		}
		
		$logo_href = $mod_prog_jackpot.find('div.jackpot a').attr('href');
		
		$mod_prog_jackpot.append('<a href="' + $logo_href + '" class="logo-link"  target="_blank"></a>').css({'position':'relative'});		

		$mod_prog_jackpot.find('a.logo-link')
		.css(
		{
			'display':'block',
			'position':'absolute',
			'top':'50px',
			'left':'15px',
			'width':'150px',
			'height':'110px'
		});
	}
};

var ExclOffers =
{	
	init:function()
	{
		if (!$('#pt-index').size()) {return false;}
		
		var $container 	= $('#mod-excl-offer');
		var $offers		= $container.find('h4');
		
		if ($offers.size() < 2) {return false;}
		
		$offers.not(':first').hide(); // Hide all offers except first
		
		var list_items = "";
		
		// Loop offers to fetch text and link from it to build a <ul>
		$offers.each(function(i) {
			
			$this = $(this);
			link = $this.find('a').attr('href');
			
			// add sel class to the first one
			class_sel = "";
			if (i == 0) {class_sel = ' class="sel"';}
			
			list_items+= '<li' + class_sel + '><a href="' + link + '" target="_blank">' + $this.text() + '</a></li>';
		});
		
		list_items = '<ul class="bullets">' + list_items + '</ul>';
		
		$container.append(list_items);
	},
	
	start:function()
	{
		if ($('#pt-index').size())
		{
			setTimeout("ExclOffers.switch_offer(0)",2000); // Start switching
		}
	},
	
	// Switch between offers from a given interval by fading in/out
	// Also move sel class in <ul> below to show which one is currently displayed
	switch_offer:function(num)
	{	
		var $container 	= $('#mod-excl-offer');
		var $offers 	= $('#mod-excl-offer h4');
		var $list_items	= $('#mod-excl-offer').find('li');

        if($list_items.size() > 1)
        {
            $offers.eq(num).fadeOut("normal",function()
            {
                next = num +1;
                if (num == $list_items.size() -1)
                {
                    next = 0;
                }
                $list_items.removeClass("sel");
                $list_items.eq(next).addClass("sel");
                $offers.eq(next).fadeIn("normal",function() {
                    setTimeout("ExclOffers.switch_offer(" + next + ")",3500);
                });
            });
        }
	}
};

var Spotlight =
{
	init:function()
	{
		if (!$('#pt-index').size()) {return false;}
		
		Screenshots.setup('#mod-spotlight div.footer ul.thumbs',false,100,'li',5);
		
		var $target = $('#mod-spotlight');
		
		if (!$target.size()) {return false;}
		
		$target.find('.footer ul.thumbs a').each(function()
		{
			$(this).click(function()
			{
				if ($('#mod-spotlight .loader').size()) {return false;} // Abort if a room is currently loading
				Spotlight.load_review($(this).attr('href'));
				return false;
			});
		});
	},
	
	load_review:function(page_href)
	{	
		var $target = $('#mod-spotlight');	// Store container
		
		if (!$target.size() || !page_href) {return false;}
		
		$target.append('<div class="temp"></div>');	// Create div to store the stuff we're fetching from review page
		
		var $temp = $target.find('.temp');		// Store temp div
		var $head = $target.find('.heading');	// Store head div
		var $body = $target.find('.body');		// Store body div
		
		$head.find('h4').css('visibility','hidden'); 	// Hide room header
		$body.find('.screenshots, .text').hide();		// Hide content to be replaced
		
		$body.append('<img class="loader" src="/css/gfx/thickbox-loader.gif" alt="loading" style="padding:75px 0 75px 180px;" />'); // Show loader
		
		$temp.hide().load(page_href + " #main",function() // Get content from #main on review page
		{
			// Get text and imgs from loaded dom element
			
			var $left_table_cells 	= $temp.find('#mod-basics .f-c table td');
			var $right_table_cells 	= $temp.find('#mod-basics .l-c table td');
			var header 				= $temp.find('#mod-basics .f-c h3').text();
			var review_text 		= $temp.find('#mod-review p:first').text();
			
			// Replace old values with new ones
			
			var $body_text 			= $body.find('.text');
			var $body_links 		= $body_text.find('ul.arrows a');
			
			if ($body_links.size())
			{
				$review_link 	= $body_links.eq(0);
				$visit_link		= $body_links.eq(1);
			}
			
			$review_link.attr("href",page_href);
			
			if ($left_table_cells.size())
			{
				var web_url = $left_table_cells.eq(1).find('a').attr('href');
				
				if (web_url && $visit_link)
				{
					$visit_link.attr("href",web_url);
				}
			}
			
			if ($right_table_cells.size())
			{
				if ($body_text.size())
				{
					var $body_header = $body_text.find('h5');
					
					if ($body_header.size())
					{
						var bonus 	= $right_table_cells.eq(0).text();
						var match 	= $right_table_cells.eq(1).text();
						
						$body_header.find('span.bonus').text(bonus);
						$body_header.find('span.match').text(match);
					}
				}
			}			
			
			if (header)
			{
				$head.find('h4').text(header);
			}
			
			if (review_text)
			{
				if ($body_text.size())
				{
					review_text = review_text.substring(0,135) + "...";
					$body_text.find('p').text(review_text);
				}
			}
			
			// Replace the screenshots
			
			var $new_screenshots = $target.find('#mod-screenshots .viewport a');
				
			var $old_screenshots = $target.find('.screenshots a');
			var num_old_screenshots = $old_screenshots.size();
			
			if ($new_screenshots.size() && num_old_screenshots)
			{
				$old_screenshots.each(function(i)
				{
					var width 		= "";
					var height 		= "";
					var class_name	= "";
					
					if (i == 0)
					{
						width 		= 227;
						height 		= 169;
						class_name	= 'big';
					}
					else
					{
						width 		= 70;
						height 		= 53;
						class_name	= '';
					}
					
					var $this 		= $(this);
					var img_src 	= $new_screenshots.eq(i).attr('href');
					
					$(this).image(img_src + '&width=' + width,function()
					{
						$(this).prev().remove().end().attr({'width':width,'height':height,'class':class_name}).parent().attr({'href':img_src});								

						if (num_old_screenshots == (i +1))
						{
							$head.find('h4').css('visibility','visible');				// Make header visible				
							$body.find('.loader').remove();								// Remove loader
							$body.find('.screenshots, .text').show(); 					// Show spotlights body content

							$temp.remove(); // Remove the temp div, we don't need it anymore
						}
					});
				});
			}			
		});
	}
};

// Function for showing customized tooltip.
// Make sure there's a nicely styled #tooltip in your css
// .tooltip may also be styled if you for example want a pointer cursor..
var ToolTip =
{
	init:function()
	{
		var $targets = $('.tooltip'); // Store all elements that wants a tooltip
		
		if (!$($targets).size()) {return false;}	// If none - bye bye
		
		$targets.each(function() // Loop targets
		{
			var $this 			= $(this);
			var display_text 	= $this.attr('title');
			
			if (!$("#tooltip").size()) // if tooltip div doesnt exist
			{
				$this.mouseover(function(e)
				{	
					$this.attr('title',''); // Remove title - we dont want both´the browser tooltip and our customized one to show one.
					
					var mouse_y = e.pageY + 10 + 'px'; // Cordinates (10 px offset on both directions)
					var mouse_x = e.pageX + 10 + 'px';

					$('body').append('<div id="tooltip" style="visibilty:none">' + display_text + '<div>'); // Append tooltip div to body

					$("#tooltip").css({top: mouse_y, left:mouse_x }); // Set x & y based on mouse's position 
				});
			}
			
			// Remove tooltip on mouseout and reset title
			$this.mouseout(function(display_text)
			{
				$("#tooltip").remove();
				$this.attr('title',display_text);
			});
			
			// make tooltip move when you move your mouse over target
			$this.mousemove(function(e)
			{
				var mouse_y = e.pageY + 5 + 'px';
				var mouse_x = e.pageX + 10 + 'px';
				
				$("#tooltip").css({top: mouse_y, left:mouse_x });
			});
		});		
	}
};

var Screenshots =
{
	init:function()
	{
		if ($('#pt-review').size())
		{
			Screenshots.setup('#mod-screenshots div.imgs',true,255,'p',2);
		}
		else
		{
			return false;
		}
	},
	
	setup:function(target_div,thickbox,img_width,img_container,min_num_imgs)
	{
		var $target = $(target_div);
		
		if (thickbox == true)
		{
			$target.find('a').addClass('thickbox');
		}
		
		var num_imgs = $target.find(img_container).size();
		
		if (num_imgs < min_num_imgs+1) {return false;}
		
		$('.viewport').after('<ul class="nav"><li class="prev"><a href="#"><span>Previous</span></a></li><li class="next"><a href="#"><span>Next</span></a></li></ul>');
		
		var $prev = $('.prev');
		var $next = $('.next');
		
		Screenshots.set_opacity($prev,0.25);
		
		var total_width 	= img_width * num_imgs;
		var end_left_pos 	= total_width - img_width * min_num_imgs;
		end_left_pos 		= parseInt("-" + end_left_pos);
		
		var speed = 250;
		//alert(total_width);
		$target.css("width",total_width + 100 + "px");
		
		$prev.find('a').click(function()
		{
			$(this).blur();
			
			if (parseInt($target.css('left')) == 0) {return false;}
			
			Screenshots.reset_opacity($prev,$next);
			
			$target.animate(
				{left: "-=-" + img_width + "px"},
				speed,
				function() {
					if (parseInt($target.css('left')) == 0) {Screenshots.set_opacity($prev,0.25);}
				}
			);
			return false;
		});
		
		$next.find('a').click(function()
		{	
			$(this).blur();
			
			if (parseInt($target.css('left')) == end_left_pos) {return false;}
			
			Screenshots.reset_opacity($prev,$next);
			
			$target.animate(
				{left: "+=-" + img_width + "px"},speed,
				function()
				{
					if (parseInt($target.css('left')) == end_left_pos) {Screenshots.set_opacity($next,0.25);}
				}
			);
			return false;
		});
	},
	
	set_opacity:function(target,opacity)
	{
		target.css('opacity',opacity);
	},
	
	reset_opacity:function(prev,next)
	{
		Screenshots.set_opacity(prev,1);
		Screenshots.set_opacity(next,1);
	}
};

window.onload = ExclOffers.start;

var ReviewCurrencies = 
{
	init:function()
	{
		if (!$('#pt-review').size()) {return false;}
				
		var $buttons = $( 'dl.currency-selector' );
		var $select = $( '#type-b select#set-currency' );
		
		if ($buttons.size())
		{
			$buttons.find( 'a' ).click(function()
			{
				$this = $( this );
				var currency = $this.attr( 'class' );

				$( 'table.bonus-info' ).addClass( 'bonus-info-hidden' ).removeClass( 'bonus-info' );
				$( '.l-c table#'+currency ).addClass( 'bonus-info' ).removeClass( 'bonus-info-hidden' );

				//$( '#mod-screenshots ul' ).addClass( 'bonus-info-hidden' ).removeClass( 'bonus-info' );
				$( '#mod-screenshots ul' ).each(function (i){
					//Don't include the flags
			        if(!$(this).hasClass('non-interactive'))
			        {
			        	//Change the buttons
			        	$(this).addClass( 'bonus-info-hidden' ).removeClass( 'bonus-info' );
			        }
			      });
				
				$( '#mod-screenshots ul#'+currency ).addClass( 'bonus-info' ).removeClass( 'bonus-info-hidden' );

				$( '#mod-review ul' ).addClass( 'bonus-info-hidden' ).removeClass( 'bonus-info' );
				$( '#mod-review  ul#'+currency ).addClass( 'bonus-info' ).removeClass( 'bonus-info-hidden' );

                $( '#mod-review div' ).addClass( 'review-text-hidden' ).removeClass( 'review-text' );
                $( '#mod-review div#review-'+currency ).addClass( 'review-text' ).removeClass( 'review-text-hidden' );

				$( '.currency-selector > .selected' ).removeClass( 'selected' );
				$this.parent().addClass( 'selected' );

				$( '#mod-screenshots ul.nav' ).removeClass( 'bonus-info-hidden' );

				return false;
			});		
		}
		
		if ($select.size())
		{
			$select.change(function()
			{
				$this = $( this );
				var currency = $this.val();
				
				$( '#type-b div.bonus-info' ).addClass( 'bonus-info-hidden' ).removeClass( 'bonus-info' );
				$( '#type-b div#'+currency ).addClass( 'bonus-info' ).removeClass( 'bonus-info-hidden' );
			
				switchCurrency(currency);
				
				return false;
				
			});
		}
	}
}

var ReviewPayments = 
{
	init:function()
	{
		if (!$('#pt-review').size()) {return false;}

        // Check if elapsed div is higher than collapsed div. If so, show a more link.
        var withdrawalStartHeight = $("#withdrawal-methods").height();
        $("div.withdrawal-methods-show").addClass( 'withdrawal-methods-hide' );
        $("div.withdrawal-methods-show").removeClass( 'withdrawal-methods-show' );
        var withdrawalHiddenHeight = $("#withdrawal-methods").height();

        if( withdrawalStartHeight > withdrawalHiddenHeight )
        {
            var link = '<a class="more-follow-withdrawal" href="">' + $( "#more-withdrawal-text" ).attr( "value" ) + '</a>';
            $( "#withdrawal-methods" ).parent().append( link );
        }
		
		$('a.more-follow').click( function()
		{	
			if( $("div.payment-methods-show").length > 0 )
			{
				$("div.payment-methods-show").addClass( 'payment-methods-hide' );				
				$("div.payment-methods-show").removeClass( 'payment-methods-show' );
				return false;
			}
			else
			{
				$("div.payment-methods-hide").addClass( 'payment-methods-show' );
				$("div.payment-methods-hide").removeClass( 'payment-methods-hide' );
				return false;
			}
						
		});
		
		$('a.more-follow-withdrawal').click( function()
		{	
			if( $("div.withdrawal-methods-show").length > 0 )
			{
				$("div.withdrawal-methods-show").addClass( 'withdrawal-methods-hide' );
				$("div.withdrawal-methods-show").removeClass( 'withdrawal-methods-show' );
				return false;
			}
			else
			{
				$("div.withdrawal-methods-hide").addClass( 'withdrawal-methods-show' );
				$("div.withdrawal-methods-hide").removeClass( 'withdrawal-methods-hide' );
				return false;
			}
						
		});

	}
}

function switchCurrency( currency )
{
    // TODO: The currency should be set in the session instead
    var today = new Date();
    var expires_date = new Date( today.getTime() + (1000 * 60 * 60) );
    
    document.cookie = 'currency=' + currency + '; expires=' + expires_date.toGMTString() + '; path=/';
}
