var cycling_images = new Array();
var timer_ids = new Array();
var slider_page = 1;


$(document).ready( function() {
    $('.cycling_container').each( function() { reformat_images( $(this).attr('id') ); } );

if($('#liveblog-hero1').length)
	{
	$.ajaxSetup ({ cache: false });
	$('#the-secret-jar1').load('/2010/06/16/konami-e3-2010-keynote-live-from-the-los-angeles-convention-cen/ .post-body',function(){
		$('#the-secret-jar1 img').parent().remove();
		var allUpdates = $('#the-secret-jar1 .post-body .live_update').length;
		for(var i=0; i<6; i++)
			{
			var timestampRaw = $('#the-secret-jar1 .post-body .live_stamp').eq(i).text();
			var timestamp = timestampRaw.replace('PM',' PM').replace('AM',' AM');
			var blurb = jQuery.trim($('#the-secret-jar1 .post-body .live_update').eq(i).text().replace(timestampRaw,''));
			$('#liveblog-hero1 .dl-liveblog-list').append('<li class="clearfix"><div class="dl-liveblog-time floatL">'+timestamp+'</div> <div class="dl-liveblog-update floatL">'+blurb+'</div></li>');
			}
		});
	}

	// PR HIDER
	$('div[id="pr_box_button"]').click(function(){
		var prIndex = $('div[id="pr_box_button"]').index(this);
		var prButton = $('div[id="pr_box_button"]').eq(prIndex);
		var prText = $('div[id="pr_text"]').eq(prIndex);
		if(prText.is(':visible'))
			{
			prText.fadeTo('fast',0,function(){
				prText.slideUp('fast');
				prButton.css('background-image','url(http://www.blogcdn.com/www.joystiq.com/media/2010/06/joy-show-pr.png)');
			});
			}
		else
			{
			prText.fadeTo('fast',0).slideDown('fast',function(){
				prText.fadeTo('fast',1);
				prButton.css('background-image','url(http://www.blogcdn.com/www.joystiq.com/media/2010/06/joy-hide-pr.png)');
			});
			}
	});

// $('td.has-posts a').live('mouseover mouseout', 
// function(event) {
//     if (event.type == 'mouseover') {
//         title = this.title;
//         $(this).attr('title', '').attr('rel', title);
//         $('td.has-posts div').stop().fadeOut('fast', 
//         function() {
//             $(this).remove();
//         });
//         $('<div>', {
//             id: 'calHover'
//         }).css({
//             'display': 'none',
//             'zIndex': '125554'
//         }).html('<p>' + title + '</p>').appendTo($(this).parents('td')).fadeIn('slow');
//     } else {
//         $(this).attr('title', $(this).attr('rel'));
//         $('#calHover').stop().fadeOut('fast', 
//         function() {
//             $(this).remove();
//         });
//     }
// });
	$('span.calendar-prev a,span.calendar-next a').live('click',function(){
		$('#archives-mod').load($(this).attr('href'));
		return false;
	});

    $('#newkey, #verifykey').keyup( function() { verify_password( false ); } );
    $('#register_form').submit( function() { if ( ! verify_password( true ) ) { return false; } });
    
    $('.tab_tag a').each( function() { $(this).attr( 'href', $(this).attr('href').replace(/\+/g, '-') ) } );
    $('.tab_search a').each( function() { $(this).attr( 'href', $(this).attr('href').replace(/-/g, ' ') ) } );
    $('.results-hdr em').each( function() { $(this).html( $(this).html().replace(/\+/g, ' ') ) } );

    // Highlight the correct sort-by tab
    if ( window.location.href.match(/\&sort/) ) { $('.tab_sort_date a').addClass('selected'); } else { $('.tab_sort_rel a').addClass('selected'); }

	// TAB HIGHLIGHTING FOR GAME HEADER
	if ( window.location.href.match(/\/game\//) )
		{
		$('.tabs .updates a').addClass('selected');
		$('#prim-nav .games a').addClass('selected');
		}
	if ( window.location.href.match(/#review/) ) { $('.tabs .review a').addClass('selected'); }
	if ( window.location.href.match(/\/video\//) && window.location.href.match(/\/game\//)  )
		{
		$('.tabs .video a').addClass('selected');
		$('#prim-nav .videos a').addClass('selected');
		$('.tabs .updates a').removeClass('selected');
		$('#prim-nav .games a').removeClass('selected');
		}
	if ( window.location.href.match(/\/screens\//)  && window.location.href.match(/\/game\//) )
		{
		$('.tabs .screens a').addClass('selected');
		$('#prim-nav .galleries a').addClass('selected');
		$('.tabs .updates a').removeClass('selected');
		$('#prim-nav .games a').removeClass('selected');
		}

    $('#slide-content').hover(
        function() { 
            $('ul.ul-next').fadeIn(); 
            if (slider_page > 1) { $('ul.ul-prev').fadeIn(); }
        },
	function() {
            $('ul.ui-controls').fadeOut(); 
        }
    );

    $('ul.ul-next a').click( function() { change_news('next'); return false; } );
    $('ul.ul-prev a').click( function() { change_news('prev'); return false; } );


    // Remove the existing "selected" link, and change it to the one based on the url.

    if (top.location.href.match(/\/videos/) || top.location.href.match(/\/screenshots/)) {
        $('ul.options li a').removeClass('selected');

        var platform = top.location.href.match(/\/videos.[a-z0-9]+/);
        if ( ! platform ) { platform = '/videos'; }
        
        if (top.location.href.match(/\/screenshots/)) { 
            platform = top.location.href.match(/\/screenshots.tag.[a-z0-9]+/); 
            if ( ! platform ) { platform = '/screenshots'; }
        }

        var selector = 'ul.options li a[href="' + platform + '"]';
        $(selector).addClass('selected');
    }

	// POPULATE PLATFORM BADGES ON GAME PAGES
	if(typeof platformPop !== 'undefined' && platformPop)
		{
        	for(i in platformPop)
        		{
        		switch(platformPop[i])
        			{
        			case 'PlayStation 2':
        			case 'PlayStation 3':
        				$('#game-header-badge-ps3').show();
        				break;
        			case 'Xbox':
        			case 'Xbox 360':
        				$('#game-header-badge-xbox').show();
        				break;
        			case 'Wii':
        				$('#game-header-badge-wii').show();
        				break;
        			case 'PC':
        				$('#game-header-badge-pc').show();
        				break;
        			case 'Nintendo DS':
        				$('#game-header-badge-ds').show();
        				break;
        			case 'PSP':
        				$('#game-header-badge-psp').show();
        				break;
        			case 'Mobile':
        				$('#game-header-badge-mobile').show();
        				break;
        			}
        		}
        	}
        	
        // DESCRIPTION HIDER/SLIDER
        if($('#game-info-description-hider').length)
        	{
        	if($('#game-info-description-inner').height() > 105)
        		{
        		$('#game-info-description-hider').css('height','105px');
        		$('#game-info-description-hider-more').show();
        		}
        	}
        $('#game-info-description-hider-more a').live('click',function(){
        	var newHeight = $('#game-info-description-inner').height();
        	$('#game-info-description-hider').animate({'height':newHeight+'px'},500);
        	$('#game-info-description-hider-more').slideUp('fast');
        	return false;
        });
        	
});


function reformat_images( container_id ) {

    var counter = 1;

    $('.cycling_image_extras').hide();

    var return_text = "<div class='cycling_images' style='display:none;'>\n";
    var caption_bar = "<div class='cycling_caption_bar'>\n";

    cycling_images['container_' + container_id] = new Array();
    var number_of_images = $('#' + container_id + ' img').length;

    $('#' + container_id + ' .cycling_image_container img').each( function() {

        var next_image_class = "cycling_image_" + counter;

        var link = $(this).parent('a').attr('href');

        if (link) { return_text += "<a href='" + link + "'>"; }
        return_text += "<img src='" + $(this).attr('src') + "' class='" + next_image_class + "'>\n";
        if (link) { return_text += "</a>"; }

        caption_bar += "<div class='cycling_caption cycling_caption_" + counter + "'><span>" 
            + $(this).attr('caption') + "</span></div>\n";

        counter++;

    } );

    caption_bar += "</div>\n";

    $('#' + container_id + " .cycling_image_container").html( return_text );
    $('#' + container_id + ' .cycling_images').show();

    $('#' + container_id).append( caption_bar );
    $('#' + container_id).append( "</div>\n" );

    var caption_width = Math.floor( $('#' + container_id).width() / number_of_images );
    var leftover = $('#' + container_id).width() - ( caption_width * number_of_images );

    $('#' + container_id + ' .cycling_caption').each( function() {
        $(this).css('width', caption_width);
        $(this).prepend("<div class='cycling_progress_bar'><div class='cycling_progress_bar_move'></div></div>");

        var current_caption = $(this).attr('class').match(/cycling_caption_\d+/).toString();
        $(this).click( function() { rotate_images( container_id, current_caption.replace(/caption/, 'image'), false ); } );
    } );

    var last_width = ( (caption_width * 1) + (leftover * 1) );
    $('#' + container_id + ' .cycling_caption:last').css( 'width', last_width );

    $('#' + container_id + ' .cycling_image_1').show();
    make_caption_active( container_id, 'cycling_caption_1', true );
    $('.' + container_id + '_cycling_image_extras_1').show();

    timer_ids[container_id] = setTimeout("rotate_images('" + container_id + "', 'next', true);", $('#' + container_id).attr('delay') * 1000);

    $('#main-carousel').hover(
        // Mouse over - kill the auto-move timer
        function() { 
            clearTimeout(timer_ids[container_id]); 
            timer_ids[container_id] = null; 

            var current_caption = $('#' + container_id + ' .cycling_caption_active').attr('class').match(/cycling_caption_\d+/);
            $('#' + container_id + ' .cycling_caption_active .cycling_progress_bar_move').stop().animate({ 'width': '0' }, 500);
        },

        // Mouse out - start the timer again
        function() {
            timer_ids[container_id] = setTimeout("rotate_images('" + container_id + "', 'next', true);", $('#' + container_id).attr('delay') * 1000);

            var current_caption = $('#' + container_id + ' .cycling_caption_active').attr('class').match(/cycling_caption_\d+/);
            make_caption_active( container_id, current_caption, true );
        } 
     );


}

function rotate_images( container_id, direction_or_id, settimer ) {

    clearTimeout(timer_ids[container_id]);
    timer_ids[container_id] = null;

    var current_image = $('#' + container_id + ' img:visible').attr('class');
    var current_image_number = current_image.match(/\d+$/);

    var next_image = "";

    if ( direction_or_id == 'back' ) {

        if (current_image_number > 1) {
            next_image = 'cycling_image_' + ((current_image_number * 1) - 1);
        } else {
            next_image = $('#' + container_id + ' .cycling_images img:last').attr('class');
        }

    } else if ( direction_or_id == 'next' ) {

        next_image = 'cycling_image_' + ((current_image_number * 1) + 1);

    } else {

        next_image = direction_or_id;

    }

    var selector = '#' + container_id + ' .' + next_image;
    if ( ! $(selector).is(':hidden') ) { next_image = 'cycling_image_1'; }

    var next_image_number = next_image.match(/\d+$/);

    $('#' + container_id + ' .' + current_image).fadeOut('500');
    $('#' + container_id + ' .' + next_image).fadeIn('500');


    $('.' + container_id + '_cycling_image_extras_' + next_image_number).parent().children('div').each( function() { $(this).fadeOut('500'); } );
    $('.' + container_id + '_cycling_image_extras_' + next_image_number).fadeIn('500');

    if (settimer == true) {
        timer_ids[container_id] = setTimeout("rotate_images('" + container_id + "', 'next', true);", $('#' + container_id).attr('delay') * 1000);
    }

    setTimeout("make_caption_active( '" + container_id + "', '" + next_image.replace(/image/, 'caption') +"', false );", 100);

}

function make_caption_active( container_id, caption_class, force_move ) {

    $('#' + container_id + ' .cycling_progress_bar').removeClass( 'cycling_progress_bar_active' );
    $('#' + container_id + ' div').removeClass( 'cycling_caption_active' );
    $('#' + container_id + ' .cycling_progress_bar_move').css('width', '0%').hide();
    setTimeout("$('#" + container_id + " .cycling_progress_bar_move').css('width', '0%').hide();", 50);

    $('#' + container_id + ' .' + caption_class + ' .cycling_progress_bar').addClass( 'cycling_progress_bar_active' );
    $('#' + container_id + ' .' + caption_class).addClass( 'cycling_caption_active' );


    if (timer_ids[container_id] || force_move == true) {
        $('.cycling_progress_bar_move').stop().hide();
        $('#' + container_id + ' .' + caption_class + ' .cycling_progress_bar_move').show().animate({ 'width': '100%' }, 
        $('#' + container_id).attr('delay') * 1000, 'linear');
    }

}

function verify_password( alertbox ) {

    if ( $('#newkey').val() && $('#verifykey').val() ) {

        if ( $('#newkey').val() != $('#verifykey').val() ) {
            $('#verify_image').attr('src', 'media/does_not_match.png').attr('title', "The passwords do not match.");
        } else {
            $('#verify_image').attr('src', 'media/matches.png').attr('title', "The passwords match.");
        }
        
        $('#verify_image').show();

        if (alertbox == true) { alert("The passwords you have entered do not match."); return false; }

    }
    
    return true;

}

function change_news( direction ) {

    var starting_position = '636px';
    var offset = '-=636px';
    
    if ( direction == 'next' ) { 
    	next_page = (slider_page * 1) + 1;
        slider_page = next_page;
        $('ul.ul-prev').fadeIn();
    } else {
        if (slider_page == 1) { return; }
        next_page = slider_page - 1;

        var starting_position = '-636px';
        var offset = '+=636px';
    }

    slider_page = next_page;
    if (slider_page == 1) { $('ul.ul-prev').fadeOut(); }


    $('#slide-content').unbind('hover');

    var ajaxurl = "/mini-hero-ajax/page/" + next_page;
 
    $.get(ajaxurl, function(response) { 

        $('#slide-content .slides').after( "<div class='slides' style='position: absolute; left: " + starting_position + "'>" + response + "</div>" );
        $('.slides').animate({"left":offset}, 'normal', 'linear', function() {
            $('.slides:last-child').css('position','relative');
            if ( $('.slides').length > 1 ) { $('.slides:first-child').remove(); }
        } );
            
    } );

}