$(document).ready(
	function()
	{
		initTabs();
		initScroll();
		
		$('#game_screens li a.screen').click(onThumbClicked);
		$('#game_screens li a.movie').click(onThumbClicked);
                $('a#first_thumb').click();
                $('#previous').hide();
		$('a.block-ui-iframe').click(onBlockUIIframe);
                $('#game_info_menu li a').click(onGameInfoChange);

                if ( typeof(first_movie) !== 'undefined' && typeof(buy_popup_automate) === 'undefined'  )
                {
                    play_first_movie();
                }

                init_pc_popup_links();
                init_popup_ext_links();

                if (typeof(buy_popup_automate) !== 'undefined')
                {
                    $('a.pc-link').click();
                }
                //init_promo_input();
	}
);

function initTabs()
{
	$('#game_menu li a').click(onTabClicked);
}

function play_first_movie()
{
            if ($.hasFlashPlayer)
            {
                    var d = new Date();

                    $('#display_area').flash(
                            {
                                    id: 'media-player',
                                    //swf: 'http://www.blitzarcade.com/swf/media-player.swf?ck='+d.getTime(),
                                    swf: 'http://www.blitz1up.com/swf/media-player.swf?ck='+d.getTime(),
                                    width: 425,
                                    height: 241,
                                    params: {
                                            bgcolor: '#000000',
                                            wmode: 'transparent',
                                            AllowScriptAccess: 'always',
                                            flashvars: {
                                                            id: first_movie,
                                                            e: 0,
                                                            b1u: 1
                                            }
                                    }
                            }
                    );
            }
            else
            {
                    $('#display_area').html('<a href="http://get.adobe.com/flashplayer/" title="Get Flash Player"><img src="/gfx/game/no-flash.jpg" alt="No flash player installed"></a>');
            }
}

function onGameInfoChange()
{
        var active_tab_id = $('#game_info_menu li a.active').attr('id');
        var active_box_id = active_tab_id.replace('tab_', '');
        var tab_id = $(this).attr('id');
        var box_id = tab_id.replace('tab_', '');

        $('#' + active_tab_id).removeAttr('class');
	$('#' + tab_id).attr('class', 'active');
        $('#' + active_box_id).css('display','none');
        $('#' + box_id).css('display','block');

        return false;
}

function onTabClicked()
{
	var active_tab_id = $('#game_menu li a.active').attr('id');
	var tab_id = $(this).attr('id');
	var active_box_id = active_tab_id.replace('tab_', '');
	var box_id = tab_id.replace('tab_', '');

        if (box_id != 'game_info_content')
        {
            $('#game_info_area').css('display','none');
        }
        else
        {
            $('#game_info_area').css('display','block');
        }

	$('#'+active_tab_id).removeAttr('class');
	$('#'+tab_id).attr('class', 'active');
	$('#'+active_box_id).hide();
	$('#'+box_id).show();

	return false;
}

function initScroll()
{
	$('ul#thumb_navigation a').click(onScrollClicked);
	curr_col = 1;
}

function onScrollClicked()
{
        //alert('onScrollClicked');

        var sign, next_pos;
	var v_jump = 214; // 8 is margin
	var curr_pos = parseInt($('#game_screens').css('left').match(/[+-]?\d+/));
	var cols = Math.floor($('#game_screens li').length / 2);
	var min_col = 1;

        //alert(cols);

	var max_col = cols - 1;
	var dir = $(this).attr('id').substr(1);

        //alert("dir:" + dir + " cols:" + cols);

	if (dir == 'left' && curr_col > 1)
	{
		sign = '+';
		next_pos = curr_col + v_jump;
		curr_col--;
	}
	else if (dir == 'right' && curr_col < max_col)
	{
		sign = '-';
		next_pos = curr_pos - v_jump;
		curr_col++;
	}

	if (curr_col == 1)
	{
		$('#previous').hide();
	}
	else
	{
		$('#previous').show();
	}

	if (curr_col == max_col)
	{
		$('#next').hide();
	}
	else
	{
		$('#next').show();
	}

//	$('#debug').prepend('curr_row: ' + curr_row + ', max_row: ' + max_row + ', min_row: ' + min_row + ', next_pos: ' + next_pos + '<br>\n');

	$('#game_screens').animate({left: sign + '=' + v_jump + 'px'}, 222);

	return false;
}

function onThumbClicked()
{
	//alert('onThumb');
	var media_type = $(this).attr('class');
	var src = $(this).attr('href');
	var media_id = $(this).attr('id');

	if (media_type == 'movie')
	{
		if ($.hasFlashPlayer)
		{
			var d = new Date();

			$('#display_area').flash(
				{
					id: 'media-player',
					//swf: 'http://www.blitzarcade.com/swf/media-player.swf?ck='+d.getTime(),
                                        swf: 'http://www.blitz1up.com/swf/media-player.swf?ck='+d.getTime(),
					width: 425,
					height: 241,
					params: {
						bgcolor: '#000000',
						wmode: 'transparent',
                                                AllowScriptAccess: 'always',
						flashvars: {
								id: media_id,
								e: 0,
								b1u: 1
						}
					}
				}
			);
		}
		else
		{
			$('#display_area').html('<a href="http://get.adobe.com/flashplayer/" title="Get Flash Player"><img src="/gfx/game/no-flash.jpg" alt="No flash player installed"></a>');
		}
	}
	else if (media_type == 'screen')
	{
		$('#display_area').html('<img src="'+src+'" alt="screenshot">');
	}

	$('div.active-item').remove();
	//$(this).append('<div class="active-item"></div>');

	return false; 
}

function onBlockUIIframe()
{
	var href = $(this).attr('href').toString();

	$.blockUI({
		message: '<iframe src="' + href + '" style="border: none; height: 460px; width: 990px;" frameBorder="0"><p>Your browser does not support iframes.</p></iframe><p class="center large b" style="margin-top: 10px"><a class="js-link unblock-ui white">Close</a></p>',
		css: {
			background: '#181818',
			border: 0,
			cursor: 'normal',
			height: '500px',
			left: ($(window).width() - 990) /2 + 'px',
			overflow: 'hidden',
			padding: '20px 20px 7px 20px',
			top:  ($(window).height() - 500) /2 + 'px',
			width: '990px'
		},
		overlayCSS: {
			cursor: 'pointer'
		}
	});
	$('.blockOverlay').attr('title','Click to close').click($.unblockUI);
	$('.unblock-ui').attr('title','Click to close').click($.unblockUI);

	return false;
}

// ADDITION OF POPUP FOR PORTALS

function init_games_list_tabs()
{
        $('.buy-link').click(init_pc_popup_links);
}

function init_pc_popup_links()
{
	$('a.pc-link').click(function(){

                var current_price = $('p.store_price').html().substr(1);
		var popup_html =  $('div.pc-popup-wrapper').html();

		$.blockUI({
			message: popup_html,
			css: get_blockui_css(),
			overlayCSS: get_blockui_overlay_css()
		});
		$('.blockOverlay, .unblock').attr('title','Click to unblock').click($.unblockUI);

                // BUY CLICK COUNTER
                var xhReq;
                if (window.XMLHttpRequest)
                {   // code for IE7+, Firefox, Chrome, Opera, Safari
                    xhReq = new XMLHttpRequest();
                }
                else
                {   // code for IE6, IE5
                    xhReq = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xhReq.open("POST", "/game/buypopup/" + game_id, false);
                xhReq.send(null);
                var serverResponse = xhReq.responseText;

                $('a#check-promo-code').click(checkPromoCode(current_price));
                $('input#google').click(onGoogleClick);
		return false;
	});
}

function checkPromoCode(current_price)
{
        $('a#check-promo-code').click(function(){
          var string = $('.blockUI form input[name=promo_code]').attr('value');
          var patt1 = /blitz1uppax/i;
          string = string.match(patt1);

          if (string != null)
          {
              var price = current_price;
              var floatVar = parseFloat(price);
              var discount = (floatVar * 0.8).toFixed(2);
              $('.blockUI p.store_price').html('&pound;' + discount);
          }
          else
          {
              $('.blockUI p.store_price').html('&pound;' + current_price);
          }
        });
}

function init_popup_ext_links()
{
	$('a.ext-link').click(function(){
		var href = $(this).attr('href');

		var popup_html = $('div.ext-link-popup-wrapper').html();
		popup_html = popup_html.replace('href=""', 'href="'+href+'"');

		$.blockUI({
			message: popup_html,
                        css: get_blockui_css(),
			overlayCSS: get_blockui_overlay_css()
		});

		$('.blockOverlay, .unblock').attr('title','Click to unblock').click($.unblockUI);

		return false;
	});
}

function get_blockui_css()
{
	var css = {
		border:		0,
                background:     0,
		cursor:		'normal',
		left:		($(window).width() - 500) /2 + 'px',
                top:		($(window).height() - 400) /2 + 'px',
		textAlign:	'left'
	};

	return css;
}

function get_blockui_overlay_css()
{
	var css = {
		cursor:		'progress',
		opacity:	.35
	};

	return css;
}

function onGoogleClick()
{
        $('form#paypal-btn').attr('action', '/checkout/order');
}