var Tank = {};
var Facebook = {};
var ExternalEvent = {};
var countryCodeOverride = null;
var defaultCountyCode = "en_US";
var footerLoaded = false;

var embedPlayerSrc = "http://www.lucasarts.com/games/theforceunleashed2/cloningtank/assets/swf/embedPlayer/embedPlayer.swf";
var embedRoot = "http://www.lucasarts.com/games/theforceunleashed2/cloningtank/";

var FACEBOOK_API_KEY = "612a00d9085b6c625d2ef47cbdfe8cb1";


//==================================================================================
// TANK
//==================================================================================

Tank.init = function() {

	var urlVariables = getUrlVars();

	if ( countryCodeOverride != null ) {
		$.cookie('countryCode' , countryCodeOverride , { expires: 365, path: '/' } );
	}
	if ( urlVariables[ "country" ] != undefined ) {
		$.cookie('countryCode' , urlVariables[ "country" ] , { expires: 365, path: '/' } );
	}
	
	if ( $.cookie('countryCode') != null ) {
		Facebook.loadFacebookConnectScript()
	}
	
	$( '#contentArea' ).offset( {top:0 , left: 0 } );
	$( '#overrideButton' ).click( Facebook.login );

	Tank.reposition();
};


Tank.flashInit = function() {

	$( '#flash' )[ 0 ].addEventListener( ExternalEvent.COUNTRY_SELECTED , "Facebook.loadFacebookConnectScript" );
	$( '#flash' )[ 0 ].addEventListener( ExternalEvent.FACEBOOK_CONNECT_REQUESTED , "Facebook.login" );
	$( '#flash' )[ 0 ].addEventListener( ExternalEvent.FACEBOOK_BUTTON_OVERRIDE , "Tank.onFacebookButtonOverride" );
	$( '#flash' )[ 0 ].addEventListener( ExternalEvent.FACEBOOK_BUTTON_OVERRIDE_END , "Tank.onFacebookButtonOverrideEnd" );
	$( '#flash' )[ 0 ].addEventListener( ExternalEvent.FACEBOOK_COMMENT , "Facebook.postFacebookComment" );
	$( '#flash' )[ 0 ].addEventListener( ExternalEvent.TRACK_EVENT , "Tracking.trackEvent" );
	$( '#flash' )[ 0 ].addEventListener( ExternalEvent.EXPERIENCE_STARTED , "Tank.loadFooter" );
	Tank.reposition();
};

Tank.embed = function() {
	
	var flashvars = {};
	flashvars.assetPath = '';
	flashvars.country = defaultCountyCode;

	var params = {};
	params.menu = 'false';
	params.allowscriptaccess = 'sameDomain';
	params.bgcolor = '000000';

	var attributes = {};
	attributes.id = 'flash';

	swfobject.embedSWF( 'assets/swf/tankloader.swf' , 'flash' , '946' , '545' , '10.0.0' , null , flashvars , params , attributes );

	
};

Tank.reposition = function() {
	
	var windowWidth = ( $(window).width() < 946 ) ? 946 : $(window).width();
	
	var tankleft = Math.round( windowWidth / 2 - $( '#contentArea' ).width() / 2 );
	var tanktop = ( $(window).height() - $('#footer').height() ) / 2 - $( '#contentArea' ).height() / 2;

	if ( tankleft < 0 ) tankleft = 0;
	if ( tanktop < 5 ) tanktop = 5;

	$( '#contentArea' ).offset( {top:tanktop , left: tankleft } );
	
	if ( !footerLoaded ) return;
	
	var footerTop = $(window).height() - $('#footer').height();
	if ( footerTop < 560 ) footerTop = 560;
		
	$( '#footer' ).offset( { top: footerTop , left: 0 } );
	var rightWidth = windowWidth - $("#columnLeft" ).width() - $("#columnCenterLeft" ).width() - $("#columnCenterRight" ).width();
	
	$("#divider" ).width( windowWidth );
	$("#columnRight" ).width( rightWidth );
	$("#columnRight" ).css( "left" , ( windowWidth - rightWidth ) );
//	$("#columnRight" ).offset( { top: $("#columnRight" ).offset().top , left: ( windowWidth - rightWidth ) } );
}

Tank.muteAudio = function(e) {
	e.preventDefault(); 
	$( '#buttonAudioToggleOff' ).css( 'display','none' );
	$( '#buttonAudioToggleOn' ).css( 'display','inline' );
	$( '#flash' )[ 0 ].muteAudio();	
};

Tank.unmuteAudio = function(e) {
	e.preventDefault(); 	
	$( '#buttonAudioToggleOff' ).css( 'display','inline' );
	$( '#buttonAudioToggleOn' ).css( 'display','none' );
	$( '#flash' )[ 0 ].unmuteAudio();	
};


Tank.showRegistrationForm = function(e) {

	e.preventDefault(); 	
	var fileURL = "assets/localized/" + $.cookie('countryCode') + "/html/registration.html";
	var contentWidth = 600;
	var contentHeight = 408;
	
	Tank.popWindow( fileURL , contentWidth , contentHeight );
	
};

Tank.showPreorder = function(e) {

	e.preventDefault(); 	
	var fileURL = "assets/localized/" + $.cookie('countryCode') + "/html/preorder.html";
	var contentWidth = 600;
	var contentHeight = 336;
	Tank.popWindow( fileURL , contentWidth , contentHeight );
	
};

Tank.popWindow = function( fileURL , contentWidth , contentHeight ) {
	
	var x = (screen.width) ? ( screen.width - contentWidth ) / 2 : 0;
	var y = (screen.height) ? ( screen.height - contentHeight ) / 2 : 0;
	var settings = 'height=' + contentHeight + ',width=' + contentWidth + ',top='+y+',left='+x+',resizable=no,status=no,menubar=no,scrollbars=no';
	window.open(fileURL,"_blank",settings);
	
};

Tank.loadFooter = function( e ) {
	$('#footer').load('assets/localized/' + $.cookie('countryCode') +  '/html/footer.html' , Tank.showFooter );	
};

Tank.showFooter = function() {

	footerLoaded = true;	

	$('#footer').css( 'display' , 'none' );
	$('#footer').fadeIn( 1000 );
	$( '#buttonAudioToggleOff' ).click( Tank.muteAudio );
	$( '#buttonAudioToggleOn' ).click( Tank.unmuteAudio );
	$( '#buttonRegister' ).click( Tank.showRegistrationForm );	
	$( '#buttonPreorder' ).click( Tank.showPreorder );	

	$(".rolloverButton").hover(
	 function()
	 {
	  this.src = this.src.replace(".gif","_over.gif");
	 },
	 function()
	 {
	  this.src = this.src.replace("_over","");
	 }
	);	
	
	Tank.reposition();
};

Tank.onFacebookButtonOverride = function( event ) {

	$( '#overrideButton' ).width( event.width );
	$( '#overrideButton' ).height( event.height );
	
	$( '#overrideButton' ).css( 'display','block' );
	$( '#overrideButton' ).css( 'top', event.top );
	$( '#overrideButton' ).css( 'left', event.left );
	
	
};

Tank.onFacebookButtonOverrideEnd = function() {
	$( '#overrideButton' ).css( 'display','none' );
}


//==================================================================================
// FACEBOOK
//==================================================================================

Facebook.loadFacebookConnectScript = function() {

  	window.fbAsyncInit = Facebook.initializeFacebookConnect;

	var e = document.createElement('script'); 
	e.async = true;
	e.src = document.location.protocol + '//connect.facebook.net/' + $.cookie('countryCode') + '/all.js';
	document.getElementById('fb-root').appendChild(e);
	  
};

Facebook.initializeFacebookConnect = function() {
	
	FB.init({
	  appId  : FACEBOOK_API_KEY,
	  status : true, // check login status
	  cookie : true // enable cookies to allow the server to access the session
	});	
	
};

Facebook.login = function() {

	FB.login( Facebook.handleFacebookLoginResponse , {perms:'publish_stream,offline_access'});	
};

Facebook.handleFacebookLoginResponse = function( response ) {

  if (response.session) {

    if (response.perms) {

		$( '#flash' )[ 0 ].handleFacebookResponse( true );

    } else {

		$( '#flash' )[ 0 ].handleFacebookResponse( false );

    }
  } else {

		$( '#flash' )[ 0 ].handleFacebookResponse( false );

  }
};


Facebook.postFacebookComment = function( event ) {

	var id = event.attachmentId;
	id = id.toLowerCase();
	FB.getSession();
	
 	FB.api(
   	{
     'method': 'stream.publish',
     'message': event.message,
     'attachment': {
       'name': event.attachmentName,
       'caption': event.attachmentCaption,
       'description': event.attachmentDescription,
       'href': event.attachmentHref,
		'media': [{
			'type':            'flash',
			'swfsrc':          embedPlayerSrc + '?country=' + $.cookie('countryCode') + '&autoplay=true&src=' + embedRoot + '?v=' +id , 
		    'imgsrc':          embedRoot + 'assets/images/visions/' + id + '.jpg', 
		    'expanded_width':  '460',
		    'expanded_height': '258'
			}]
     }
   }, Facebook.handlePostFacebookResponse );
};

Facebook.handlePostFacebookResponse = function( response ) {


	
};

//==================================================================================
// UTILS
//==================================================================================

function getUrlVars() {

    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

//==================================================================================
// EXTERNAL EVENT
//==================================================================================


ExternalEvent.COUNTRY_SELECTED = "onCountrySelected";
ExternalEvent.FACEBOOK_CONNECT_REQUESTED = "onFacebookConnectRequested";
ExternalEvent.FACEBOOK_BUTTON_OVERRIDE = "onFacebookButtonOverride";
ExternalEvent.FACEBOOK_BUTTON_OVERRIDE_END = "onFacebookButtonOverrideEnd";
ExternalEvent.FACEBOOK_COMMENT = "onFacebookComment";
ExternalEvent.TRACK_EVENT = "onTrackEvent";
ExternalEvent.EXPERIENCE_STARTED = "onExperienceStarted";

$( document ).ready( Tank.init );
$( window ).resize( Tank.reposition );
Tank.embed();


