var maxLMFriends = 20;
var maxLMPerFriend = 2500;
var numberOfLMFriends = 0;

var bucketList = new Array();
var questions = new Array();
var questionId = 0;

// build out all the arrays
for (i=0; i<=4; i++)
{
  questions[i] = new Array();
  for (j=0; j<=4; j++)
  {
    questions[i][j] = new Array();
  }
}

questions[0]['question'] = 'You\'re sitting in class with your crush.<br />How do you get their attention?';
questions[0][0]['answer'] = 'Charm them with your devilishly good looks and positive attitude.';
questions[0][0]['bucket'] = 0;
questions[0][1]['answer'] = 'Ask them what kind of music they listen to.';
questions[0][1]['bucket'] = 1;
questions[0][2]['answer'] = 'Dramatically drop your books in front of them.';
questions[0][2]['bucket'] = 2;
questions[0][3]['answer'] = 'Tell them how much you hate being single, even if you\'re not.';
questions[0][3]['bucket'] = 3;
questions[0][4]['answer'] = 'Tell them a funny joke so they open up.';
questions[0][4]['bucket'] = 4;  

questions[1]['question'] = 'It worked! Now where will you take your<br />crush on your first date?';
questions[1][0]['answer'] = 'A club so I can get dressed up and look my best.';
questions[1][0]['bucket'] = 2;
questions[1][1]['answer'] = 'A concert by their favorite band.';
questions[1][1]['bucket'] = 1;
questions[1][2]['answer'] = 'My room, *wink-wink*';
questions[1][2]['bucket'] = 3;
questions[1][3]['answer'] = 'The beach; it\'ll be super sunny and fun!';
questions[1][3]['bucket'] = 0;
questions[1][4]['answer'] = 'The library; I\'m swamped with homework!';
questions[1][4]['bucket'] = 4;  

questions[2]['question'] = 'Your crush wants to know about your dating past. What do you say?';
questions[2][0]['answer'] = 'It\'s always been a bit complicated, but nothing I can\'t handle.';
questions[2][0]['bucket'] = 4;
questions[2][1]['answer'] = 'It\'s been a little rocky, but I\'ve been thinking about settling down.';
questions[2][1]['bucket'] = 3;
questions[2][2]['answer'] = 'I\'ve dated a lot in the past; I can\'t help it that so many people love me!';
questions[2][2]['bucket'] = 2;
questions[2][3]['answer'] = 'My past is pretty normal, nothing crazy to report.';
questions[2][3]['bucket'] = 1;
questions[2][4]['answer'] = 'There are so many ups and downs; I don\'t know where to begin!';
questions[2][4]['bucket'] = 0; 

questions[3]['question'] = 'Congratulations! You and your crush have made it official and it\'s your one-month anniversary. What will you get them?';
questions[3][0]['answer'] = 'A mix CD.';
questions[3][0]['bucket'] = 1;
questions[3][1]['answer'] = 'A framed picture of the two of you.';
questions[3][1]['bucket'] = 3;
questions[3][2]['answer'] = 'A funny poem you wrote.';
questions[3][2]['bucket'] = 4;
questions[3][3]['answer'] = 'A mood ring.';
questions[3][3]['bucket'] = 0;
questions[3][4]['answer'] = 'A framed picture of you.';
questions[3][4]['bucket'] = 2; 

questions[4]['question'] = 'Uh-oh, you\'ve been dumped! How are you going to deal with this?';
questions[4][0]['answer'] = 'Grin and bear it, even though you\'re in pain.';
questions[4][0]['bucket'] = 4;
questions[4][1]['answer'] = 'Listen to your favorite break-up songs.';
questions[4][1]['bucket'] = 1;
questions[4][2]['answer'] = 'Find someone new to pursue right away.';
questions[4][2]['bucket'] = 3;
questions[4][3]['answer'] = 'Go out and flirt up a storm.';
questions[4][3]['bucket'] = 2;
questions[4][4]['answer'] = 'Get super depressed and wear lots of black.';
questions[4][4]['bucket'] = 0;
              


$(document).ready(function() {
  $('#launchNokiaTwistedCelebrity').unbind( 'click' ).click(function( ){
    startEngagement( false );
  }); 
});

function checkForFlash( )
{

  var hasFlash = false;
  var playerVersion = swfobject.getFlashPlayerVersion();
  if(playerVersion.major >= 9)
  {
    var hasFlash = true;
  }
  
  return hasFlash;
    
}

function startEngagement( receiveId )
{

  contentStr = '<div id="launchEngagementPopup"><br /><br /><img src="' + IMAGE_URL + '/ajaxload_circ2.gif"><br />Launching...</div>';
  profileWidgetPopup = $('<div />').appendTo('body').dragonDrop({ width:240, title:'Launching...', content:contentStr, enableMinMax:false, curtain: false });

  $( 'iframe,embed,object' ).css({ 'visibility': 'hidden' });
  $( '.FriendsFeed' ).css( { 'overflow-y': 'hidden' } );
  $( '.quizWrapper' ).css( { 'display': 'none' } );
  $( '.postText' ).css( { 'overflow': 'hidden' } );
  $( '#HALFounderBulletins .msg' ).css( { 'overflow': 'hidden' } );
                
  $('<div id="engagement" />').appendTo('body').dragonDrop({
    type: 'window',
    curtain: true,
    curtainColor: '#fff',
    curtainOpacity: 0.5,
    enableClose: false,
    displayClass: 'dragonTransparent',
    content: "<div id='engagementData'></div>",
    enableMinMax: false,
    top: 0,
    centerTopEdge: false,
    draggable: false
  });
  
  if ( receiveId )
  {

    if ( checkForFlash( ) )
    {
      showPage( 'receive', receiveId );
    } else {
      showPage( 'receiveResult', receiveId );
    }
  } else {
    if ( checkForFlash( ) )
    {
      showPage( 'launch' );
    } else {
      showPage( 'quiz' );
    }
  }

}

function showPage( page, data )
{
  
  profileWidgetPopup.fadeOut(200,function(){$(this).remove();});

  $.ajax({
    type:'post',
    url:'/apps/engagements/NokiaTwistedCelebrity/' + page + '/',
    data:'data=' + data,
    dataType:'json',
    success:function( data )
    {
      
      $('#engagementData').html ( unescape( data.output.replace(/\+/g, ' ') ) );
      
      if ( data.flash )
      {
        eval( data.flash );
      }

      if ( page == 'launch' )
      {
      
        urchinTracker( 'myb/home/cep/nokia/halclicks' );
             
      } 
      else if ( page == 'quiz' )
      {

        showQuestion( );
        
      }
      else if ( page == 'result' )
      {

        $('#resultPageStartOver').click(function( ){
          showPage( 'quiz' );
        }); 
        
        $('#resultPageAddToProfile').click(function( ){
          addWidget( );
        });   
        
        $('#resultPageSendToFriends').click(function( ){
          showPage( 'invite' );
        }); 
                      
      }
      else if ( page == 'invite' )
      {
      
        RequestsSender.initialize();
        $('.loading').remove();
        
        numberOfLMFriends = data.LMFriends;
        invitePageBonusAvailable( );       
        if ( gomez.pgId == 'Profile' )
        {
          if ( $.browser.msie )
          {
            $('#engagementData .selectorContainer').css('margin-top','8px');
          }
        } else {
          if ( $.browser.mozilla || $.browser.msie )
          {
            $('#engagementData .selectorContainer').css('margin-top','11px');
          } 
        }
        
      }         
      else if ( page == 'inviteSent' )
      {
        
        $('#inviteSentStartOver').click(function( ){
          showPage( 'quiz' );
        });  
          
        $('#inviteSentClose').click(function( ){
          closeEngagement( );
        });  
                     
      }
      else if ( page == 'receiveResult' )
      {
        
        $('#receiveResultPageTakeTheQuiz').click(function( ){
          showPage( 'quiz' );
        });  

        $('#receiveResultPageOptOutButton').click(function( ){
          showOptOut( );
        });  
                             
      }
      
      // hacky way to know if we're on the profile or not
      if ( gomez.pgId == 'Profile' && ( $.browser.safari || $.browser.mozilla ) )
      {
        $('#engagementData #' + page + 'Page').css('margin-top','-3px');
        $('#engagementData #leftAdSide').css('margin-top','-3px');
      }

      // set on every page load
      $('#closeEngagement').unbind( 'click' ).click(function( ){
        closeEngagement( );
      });
      
      $('#visitSite').unbind( 'click' ).click(function( ){
        urchinTracker('myb/cep/nokia/officialclicks');
        window.open( 'http://www.nokia.com/' );
      });

      $('#leftAdSide').unbind( 'click' ).click(function( ){
        urchinTracker('myb/cep/nokia/veizonlogoclicks');
        window.open( 'http://phones.verizonwireless.com/nokia/twist/' );
      });
    }
    
  });
  
}

function addWidget( )
{

  var hash = $('#resultPageHash').html( );
  var result = $('#resultPageResult').html( );

  $.ajax({
    url:'/ajax/engagements/addWidget.php',
    type:'post',
    dataType:'json',
    data:'engagementName=NokiaTwistedCelebrity&data=' + result + '&hash=' + hash,
    success:function( data )
    {
    
      $('<div id="errorBox" />').appendTo( 'body' )
  		.dragonDrop({
  			type:'window',
  			title:'Add Widget',
  			content: 'Successfully added the widget to your profile.',
  			enableMinMax: false,
  			enableClose : true,
  			width:400
  		});
  		
    }
  }); 

  return false;
        
}

function showOptOut( )
{

  $('#confirmOptOutBox').css('display','block');
  
  $('#confirmOptOutBoxYes').unbind( 'click' ).click(function( ){
    optOutEngagement( );
  });
  
  $('#confirmOptOutBoxNo, #confirmOptOutClose').unbind( 'click' ).click(function( ){
    $('#confirmOptOutBox').css('display','none');
  });  
  
}

function optOutEngagement( )
{

  $.ajax({
    type:'post',
    url:'/apps/engagements/NokiaTwistedCelebrity/optOutEngagement/',
    dataType: 'json',
    success:function( data )
    {
      closeEngagement( );
    }
  });  
  
}

function closeEngagement( )
{

  $( 'iframe,embed,object' ).css({ visibility: 'visible' });
  $( '.FriendsFeed' ).css( { 'overflow-y': 'scroll' } );
  $( '.quizWrapper' ).css( { 'display': 'block' } );
  $( '.postText' ).css( { 'overflow': 'auto' } );
  $( '#HALFounderBulletins .msg' ).css( { 'overflow': 'auto' } );  
  
  $.dragonCurtainRemove(); 
  
  RequestsSender.reset( );
  $('#dragonCurtain').remove();
  $('#engagement').fadeOut( 300, function(){ $( this ).remove(); });  
  
  // set you back to the first question
  questionId = 0;
  
}

function invitePageInvite( )
{

  if ( RequestsSender.selectedCount > 0 )
  {
  
    $.ajax({
      type:'post',
      url:'/apps/engagements/NokiaTwistedCelebrity/inviteFriends/',
      dataType: 'json',
      data: { friends: RequestsSender.buildFriendsString( ) },
      success:function( data )
      {
        RequestsSender.reset( );
        showPage( 'inviteSent' );
      }
      
    });  
    
  }  
  
}

function invitePageCountFriendsSelected( )
{
  data = RequestsSender.selectedCount;
  
  if ( RequestsSender.selectedCount == 1 )
  {
    data += ' Friend';
  } else {
    data += ' Friends';
  }
  $('#invitePageCountFriendsSelected').html( data );
}

function invitePageBonusBoxAmount( )
{
          
  bonusAvailable = ( numberOfLMFriends * maxLMPerFriend ) - ( maxLMPerFriend * RequestsSender.selectedCount );
  if ( RequestsSender.selectedCount <= maxLMFriends && bonusAvailable >= 0 )
  {
    data = maxLMPerFriend * RequestsSender.selectedCount;
    $('#invitePageBonusBoxAmount').html( 'L$' + number_format( data, 2, '.', ',') );
  }
}

function invitePageBonusAvailable( )
{
  data = ( numberOfLMFriends * maxLMPerFriend ) - ( maxLMPerFriend * RequestsSender.selectedCount );
  if( data >= 0 )
  {
    $('#invitePageBonusAvailableAmount').html( 'L$' + number_format( data, 2, '.', ',') );
  }
}

// need to make it change values below the friend selector, so copying it over here.
RequestsSender.alterSelectedCount=function( difference )
{

  if ( $.browser.safari && gomez.pgId == 'Profile' )
  {
    $('#engagementData .selectorContainer').css('margin-top','-3px');
  }
  
  if ( ( RequestsSender.selectedCount >= RequestsSender.maxSelected && difference >= 1 ) || ( RequestsSender.maxFriendsPer > 0 && RequestsSender.selectedCount >= RequestsSender.maxFriendsPer && difference >= 1 ) )
  {
    RequestsSender.displayError( 'You\'ve selected the maximum number of friends allowed.', 2500 );
    return false;
  }
  else {
    var remainingCount = ( RequestsSender.maxSelected - RequestsSender.selectedCount - difference );
    if ( remainingCount <= 3 && remainingCount != 0 )
    {
      $('#RequestSender .remainingWarning').text( 'Only ' + remainingCount + ' more...' );
    }
    else if ( remainingCount == 0 )
    {
      $('#RequestSender .remainingWarning').text( 'Limit is ' + RequestsSender.maxSelected );
    }
    else 
    {
      $('#RequestSender .remainingWarning').text( '' );
    }
    
    RequestsSender.selectedCount = RequestsSender.selectedCount + difference;
    $('#RequestSender .selectedCount').text( RequestsSender.selectedCount );
      
    invitePageCountFriendsSelected( );
    invitePageBonusBoxAmount( );
    invitePageBonusAvailable( );
    invitePageCheckForUserClicked( );
    return true;
  }
  
}


function invitePageCheckForUserClicked( )
{
  if( RequestsSender.selectedCount > 0 )
  {
    $('#invitePageInviteButton').attr('id', 'invitePageInviteButtonActive');  

    $('#invitePageInviteButtonActive').unbind('click').click(function( ){
      invitePageInvite( );
    });  
        
  } else {
    $('#invitePageInviteButtonActive').attr('id', 'invitePageInviteButton');  
  }
}

function showQuestion( )
{

  if ( questionId > 4 )
  {
    questionId = 0;
  }

  $('#quizPageQuestion').html( (questionId+1) + '. ' + questions[questionId]['question'] );
  $('#quizPageNextButtonSelected').attr('id', 'quizPageNextButton');
  $('#quizPageNextButton').unbind('click');
  
  var data = '';
  jQuery.each(questions[questionId], function() {
    data += "<input type='radio' name='question' class='question' value='" + this.bucket + "' id='" + this.bucket + "' /><label for='" + this.bucket + "'>" + this.answer + "</label><br />";
  });

  if( questionId == 3 )
  {
    $('#quizPageAnswers').css('top','90px');
  } else {
    $('#quizPageAnswers').css('top','60px');
  }
  
  $('#quizPageAnswers').html( data );

  $(".question").unbind('click').click(function () { 
  
    $('#quizPageNextButton').attr('id', 'quizPageNextButtonSelected');

    $("#quizPageNextButtonSelected").unbind('click').click(function ( )
    { 
  
      bucketList[questionId] = $('input[name=question]:checked').val( );    
      questionId++;
  
      if ( questionId < 5 )
      {
        showQuestion( ); 
      } else {
  
        result = calculateResult( );
        resultLength = result.length;
        
        // choose a random answer if the mode is an array
        if( resultLength > 1 )
        {
          result = result.split(',');
          result = result[Math.floor(Math.random()*resultLength)];
        }

        // something terrible happened or there is no mode, pick a random person.
        if ( result == undefined )
        {
          result = bucketList[Math.floor(Math.random()*bucketList.length)]; 
          // alert('result - ' + result);       
        }
  
        showPage( 'result', result ); 
  
      }
      
    });
  
  });
  
}

function calculateResult( )
{
	var tot = bucketList.length;
	var resal = sorting(bucketList);
	var modeval=0;
	var maxval=0;
	var mode,curval;
	curval = resal[0];
	for(var z=0; z<=tot; z++)
	{
		var zval = resal[z];
		if(zval == curval)
		{
			modeval=modeval+1;
			if(modeval > maxval)
			{
				mode = curval;
				maxval = modeval;
			}
		}
		else
		{
			if(modeval == maxval && mode != curval)
			{
				mode = mode+","+curval;
			}
			curval = zval;
			modeval = 1;
		}			
	}
  return mode;
}

function sorting(bucketList)
{
	var sortnum = true;
	var pos = 0;
	tot = bucketList.length;
	while(sortnum == true)
	{
		for(var j=(pos+1); j<tot; j++)
		{
			var rd = parseFloat(bucketList[pos]);
			var fg = parseFloat(bucketList[j]);
			if(rd > fg)
			{
				bucketList[pos] = fg;
				bucketList[j] = rd;
			}
		}
		pos = pos+1;
		if(pos >= tot)
		{
			sortnum=false;
		}
	}
	return bucketList;
}

function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 return f[0];
}