/**
 * VIPGift JavaScript objects
 */
function VIPGiftGive( memberId, giveCallback )
{
  // constructor actions
  var _this = this;
  this.giveCallback = giveCallback;
  IMAGE_URL.charAt(-1) != '/' ? IMAGE_URL2 = IMAGE_URL+'/' : IMAGE_URL2 = IMAGE_URL ;

  this.setDefaults = function( )
  {
    this.memberId = memberId;
    this.jQueryObj = $('#VIPGifts');
    this.flashObjId = 'VIPGiftPreview';
    this.flashMusicObjId = 'VIPGiftMusicPreview';
    this.flashObjVisible = false;
    this.giftName = '';
    this.giftJSONObj = null;
    this.giftCustomizations = { };
    this.giftCustomizationPrices = { };
    this.giftCustomizationDisplay = { };
    this.message = '';
    this.isPrivate = false;
    this.isAnonymous = false;
    this.customNote = ''; // used by gift love_note
    this.outfitCustomizations = { // used by gift beargram
      'top' : true,
      'bottom' : true,
      'hat' : true,
      'bag' : true,
      'jewelry' : true,
      'glasses' : true,
      'shoes' : true
    };
  };
  this.setDefaults( );

  $.evalWithStatus( function( ){
    _this.ajax({ action : 'build', memberId : memberId }, function( obj ){
      $.evalWithStatusComplete( true );
      if ( obj.content )
      {
        _this.jQueryObj = $(obj.content).appendTo('body').dragonDrop({
         draggable : false,
         type      : 'box',
         curtain   : false
        });
        _this.jQueryObj.find('.btn.close').bind('click', function(e) {
          _this.close( );
        });
        _this.jQueryObj.find('.getMore').bind('click', function(e) {
          e.preventDefault( );
          window.open( $(this).attr('href') );
        });

        _this.gotoSelect( false );
      }
      else
      {
        _this.error( obj.error );
      }
    });
  });


  // methods
  this.gotoSelect = function( adjustSize )
  {
    this.jQueryObj.find('#VIPGifts-wrapper').attr('class', '');
    this.jQueryObj.find('.breadcrumbs span').removeClass('breadcrumbBlue').filter('.black').remove( );
    if ( adjustSize )
    {
      this.adjustSize( );
    }
    this.jQueryObj.find('.select .top .right .more span').unbind( )
      .toggle(
        function(e) {
          _this.jQueryObj.find('.select .top .moreContent').slideDown('slow');
          _this.jQueryObj.css('height', 'auto');
        },
        function(e) {
          _this.jQueryObj.find('.select .top .moreContent').slideUp('slow');
        }
      );
    this.jQueryObj.find('.select .top .moreContent .moreClose span').unbind( )
      .bind('click',function(e) {
        _this.jQueryObj.find('.select .top .right .more span').trigger('click');
      });

    this.jQueryObj.find('.select .gift').unbind( )
      .bind('mouseover', function(e) {
        $(this).addClass('giftOver');
      }).bind('mouseout', function(e) {
        $(this).removeClass('giftOver');
      }).bind('click', function(e) {
        _this.giftName = $(this).children('.giftName').text();
        //window.scroll( 0, parseInt( _this.jQueryObj.css('top') ) - 5 );
        _this.jQueryObj.height( _this.jQueryObj.height( ) );
        _this.jQueryObj.find('.select').hide('slow', function( ) {
          _this.ajax({ action : 'create', giftName : _this.giftName }, function( obj ){
            _this.giftJSONObj = obj;
            _this.giftCustomizations = obj.customizations;

            var content = $(obj.content).hide( );
            var flashContent = $(obj.flashContent);

            _this.jQueryObj.find('#VIPGifts-wrapper').append( content );
            _this.jQueryObj.find('.stepContainer').css('left', _this.jQueryObj.width( ) );

            _this.jQueryObj.find('.previewArea').append( flashContent );
            flashContent.hide( );
            eval( obj.flashScript );
            if ( typeof Meebo != "undefined" && $.isFunction( Meebo.registerFlashObj ) )
            {
              Meebo.registerFlashObj( $('#'+_this.flashObjId).get(0) );
              Meebo.registerFlashObj( $('#'+_this.flashMusicObjId).get(0) );
            }

            _this.gotoCreate( );
            _this.bindActions( );
          });
        });
      });
  };

  this.gotoCreate = function( )
  { 
    _this.jQueryObj.find('#VIPGifts-wrapper').attr('class', '').addClass('wrapperCreate');
    // update L$ & cost
    $( '#VIPGifts-wrapper div.vipLM span.value' ).html( 'L$' + _this.giftJSONObj.VIPMember.lunchMBalance.str + ' ' );
    var cost = "L$0K";
    if ( _this.giftJSONObj.VIPMember.isVIP && _this.giftJSONObj.VIPMember.freeGiftLeft > 0 )
    {
      cost = "FREE";
    }
    var appendCrumb = '<span class="black">&nbsp;&raquo;&nbsp;</span>';
    appendCrumb += '<span class="black">' + _this.giftJSONObj.VIPGift.gift_display_name + '&nbsp;</span>';
    appendCrumb += '<span class="black cost">(Cost: <span class="value">' + cost + '</span>)</span>';
    _this.jQueryObj.find('.breadcrumbs span').removeClass('breadcrumbBlue').filter('.black').remove( );
    _this.jQueryObj.find('.breadcrumbs')
      .find('span').addClass('breadcrumbBlue').bind('click', function(e) {
        _this.jQueryObj.find('.stepSelector, .stepContainer, .preview').remove( );
        _this.jQueryObj.find('.select').show('slow', function( ) {
          _this.setDefaults( );
          _this.gotoSelect( true );
        });
      }).end( )
      .append( appendCrumb );

    _this.jQueryObj.find('.stepSelector .step').removeClass('stepOn');
    _this.jQueryObj.find('.stepSelector .stepCreate').addClass('stepOn');

    //window.scroll( 0, parseInt( _this.jQueryObj.css('top') ) - 5 );

    _this.adjustSize( function( ){
      _this.jQueryObj.find('.stepSelector, .preview').slideDown('slow', function( ) {
        _this.jQueryObj.find('.freeGiftNote').show( ).animate({
          left : 0
        }, 'slow', 'linear', function( ) {

        });
        _this.jQueryObj.find('.stepContainer').show( ).animate({
          left : 0
        }, 'slow', 'linear', function( ) {

        });
      });
    });
  };

  this.gotoCustomize = function( )
  {
    if ( !_this.promptUser( _this.jQueryObj.find('.create'), _this.gotoCreate, false ) )
    {
      _this.jQueryObj.find('.stepSelector .step').removeClass('stepOn');
      _this.jQueryObj.find('.stepSelector .stepCustomize').addClass('stepOn');
      //window.scroll( 0, parseInt( _this.jQueryObj.css('top') ) - 5 );
      _this.jQueryObj.height( _this.jQueryObj.height( ) );
      _this.jQueryObj.find('.stepContainer').animate({ left : _this.jQueryObj.width( ) * -1 }, 'slow' );
    }
  };

  this.gotoSend = function( )
  {
    if ( !_this.promptUser( _this.jQueryObj.find('.create') ) )
    {
      _this.jQueryObj.find('.stepSelector .step').removeClass('stepOn');
      _this.jQueryObj.find('.stepSelector .stepSend').addClass('stepOn');
      //window.scroll( 0, parseInt( _this.jQueryObj.css('top') ) - 5 );
      _this.jQueryObj.height( _this.jQueryObj.height( ) );
      _this.jQueryObj.find('.stepContainer').animate({ left : _this.jQueryObj.width( ) * -2 }, 'slow' );
    }
  };

  this.nextStep = function( clickedNextStep )
  {
    var nextTab = clickedNextStep.parents('.create, .customize').find('.tabsContainer .tabSelected').next('.tab');
    if ( nextTab.length > 0 )
    {
      // click the next tab
      nextTab.find('span').trigger('click');
    }
    else
    {
      // goto next step (no more tabs to click in this step)
      _this.jQueryObj.find('.stepSelector .stepOn').next('.step').find('span').trigger('click');
    }
  };

  this.promptUser = function( promptsParent, continueCallback, allowGive )
  {
    $('#VIPGift-prompt').slayDragon( );
    var prompts = promptsParent.find('.prompt');
    if ( prompts.length < 1 )
    {
      return false;
    }
    else
    {
      var msgPrompts = '';
      if ( prompts.length == 1 )
      {
        msgPrompts += prompts.text( );
      }
      else
      {
        prompts.each(function(i) {
          msgPrompts += ' ' + $(this).text( );
          if ( i == prompts.length - 1 ) // last one
          {
            msgPrompts += '';
          }
          else if ( i == prompts.length - 2 )
          {
            allowGive ? msgPrompts += ' or ' : msgPrompts += ' and ' ;
          }
          else
          {
            msgPrompts += ', ';
          }
        });
      }

      if ( allowGive )
      {
        var msg = 'You have not customized your ' + msgPrompts + '. Use the tabs to further customize your VIP Gift or click "Give Gift".';
        $.dragonConfirm( msg, {
          title      : 'Are You Sure?',
          cancelImg  : 'images/buttons/customize.gif',
          confirmImg : 'images/buttons/give_gift.gif',
          curtain    : false,
          cancelCallback  : function( ) {
            if ( $.isFunction( continueCallback ) )
            {
              continueCallback( );
            }
          },
          confirmCallback : function( ) {
            _this.give( );      
          }
        }).attr('id', 'VIPGift-prompt');
      }
      else
      {
        var msg = 'You must choose a ' + msgPrompts + ' before continuing.';
        $.dragonAlert( msg, {
          title      : 'Wait!',
          curtain    : false,
          okCallback  : function( ) {
            if ( $.isFunction( continueCallback ) )
            {
              continueCallback( );
            }
          }
        }).attr('id', 'VIPGift-prompt');
      }
      return true;
    }
  };

  this.give = function( )
  {
    if ( this.isPrivate && this.isAnonymous )
    {
      this.isPrivate = false;
    }

    var data = {
      action         : 'give',
      memberId       : this.memberId,
      giftName       : this.giftName,
      message        : this.message,
      customizations : $.param( this.giftCustomizations ),
      isPrivate      : this.isPrivate,
      isAnonymous    : this.isAnonymous
    };
    if ( this.giftName == 'love_note' )
    {
      data.customNote = this.customNote;
    }
    this.ajax( data, function( obj ){
      if ( obj.success )
      {
        if ( $.isFunction( _this.giveCallback ) )
        {
          _this.giveCallback( obj.given_to, obj.given_by );
        }
        _this.setDefaults( );
        _this.jQueryObj.find('.stepSelector, .stepContainer, .preview').remove( );
        _this.jQueryObj.find('.select').addClass('success')
          .find('.top, .instruction, .freeGiftTrial, .freeGiftNote').remove( ).end( )
          .prepend( obj.content ).show('slow', function(e) {
            _this.gotoSelect( true );
          });
        // update L$ after give the gift
        $( '#VIPGifts-wrapper div.vipLM span.value' ).html( 'L$' + obj.VIPMember.lunchMBalance.str + ' ' );
      }
      else if ( obj.error == 'transaction' )
      {
        var htmlContent = '<div class="details">This VIP Gift costs <span class="value">L$' + obj.cost + 'K</span>.<br /><br />';
        htmlContent += 'You currently have <span class="value">L$' + obj.VIPMember.lunchMBalance.str + '</span>.</div>';
        $.dragonAlert( '', {
          curtain : false,
          title : 'Get More Lunch Money',
          okImg : 'images/vip/btn_lg_buy_more_lm.gif',
          okCallback : function( ) {
            _this.jQueryObj.find('.getMore').trigger('click');
          }
        }).attr('id', 'VIPGift-buyAlert').find('.dragonDialog').prepend( htmlContent );
      }
      else
      {
        _this.error( );
      }
    });
  };

  this.close = function( )
  {
    $( 'div.colorPicker' ).hide( );
    this.jQueryObj.slayDragon( null, true );
  };

  this.adjustSize = function( callbackFunc )
  {
    var newHeight = this.jQueryObj.find('#VIPGifts-wrapper').height( );
    this.jQueryObj.animate({
      height : newHeight
    }, 'slow', 'linear', function( ){
      _this.jQueryObj.centerOnScreen( true );
      if ( $.isFunction( callbackFunc ) )
      {
        callbackFunc( );
        callbackFunc = null;
      }
    });
  };

  this.updateGiftUsage = function( )
  {
    var newPrice = 0;
    var outfitPrice = 0;
    $.each( _this.giftCustomizations, function( name, value ) {
      var price = _this.giftCustomizationPrices[ name ] ? parseInt( _this.giftCustomizationPrices[ name ] ) : 0 ;

      var displayName = '';
      if ( name != 'background' ) // backgrounds are not named
      {
        displayName = _this.giftCustomizationDisplay[ name ] ? _this.giftCustomizationDisplay[ name ] : 'none' ;
      }
      var currentObj = _this.jQueryObj.find('.current_' + name + ':visible > span').text( displayName + ' ' );
      if ( _this.giftCustomizations[ name ] && _this.giftCustomizations[ name ] != 'none' )
      {
        if ( name != 'background' )
        {
          var display_price = ( _this.giftJSONObj.VIPMember.isVIP && _this.giftJSONObj.VIPMember.freeGiftLeft > 0 ) ? 'FREE' : 'L$' + price + 'K';
          currentObj.append( $('<span>(</span><span class="price">' + display_price + '</span><span>) </span>') );
        }

        // allow beargram outfits and outfit customizations to be "cleared"
        if ( _this.outfitCustomizations[ name ] || name == 'outfit' || name == 'background' )
        {
          var currentClear = $('<span class="clearCurrent">Clear</span>').bind('click', function(e) {
            _this.clearCustomization( name );
          });
          currentObj.append( currentClear );
        }
      }

      // always consider outfit prices as 0 when calculating sum
      if ( name == 'outfit' )
      {
        price = 0;
      }

      // if part of an outfit, add to outfit total price
      if (  _this.outfitCustomizations[ name ] )
      {
        outfitPrice += price;
      }

      _this.jQueryObj.find('.customization.' + name + ':visible .option .price').each( function(i) {
        $(this).children('.rel').remove( );
        if ( price > 0 )
        {
          var optPrice = parseInt( $(this).children('span:not(.rel)').text( ) );
          var relPrice = optPrice - price;
          var posNeg = relPrice >= 0 ? '+' : '' ;
          $(this).append('<span class="rel">&nbsp;(' + posNeg + relPrice + 'K)</span>');
        }
      });
      newPrice += price;
    });

    var display_outfitPrice = ( _this.giftJSONObj.VIPMember.isVIP && _this.giftJSONObj.VIPMember.freeGiftLeft > 0 ) ? 'FREE' : 'L$' + outfitPrice + 'K';
    var display_newPrice = ( _this.giftJSONObj.VIPMember.isVIP && _this.giftJSONObj.VIPMember.freeGiftLeft > 0 ) ? 'FREE' : 'L$' + newPrice + 'K';
    if ( _this.giftName == 'beargram' )
    {
      _this.jQueryObj.find('.current_outfit .price').text( display_outfitPrice );
      //_this.jQueryObj.find('.current_outfit .price').text( outfitPrice );
    }

    _this.jQueryObj.find('.breadcrumbs .cost .value').text( display_newPrice );
    //_this.jQueryObj.find('.breadcrumbs .cost .value').text( newPrice );
    if ( _this.giftCustomizations['outfit'] == '' )
    {
      _this.jQueryObj.find('.current_outfit:visible .price').text( display_newPrice );
      //_this.jQueryObj.find('.current_outfit:visible .price').text( newPrice );
    }
  };

  // only used by beargram clothing, for now
  this.clearCustomization = function( customizationValue )
  {
    if ( customizationValue != 'outfit' )
    {
      _this.jQueryObj.find('.customization.' + customizationValue + ' .option:first').clone( true )
        .find('.value').text('none').end( )
        .find('.price span').text('0').end( )
        .addClass('tempClearOption').css('display','none')
        .appendTo('.customization.' + customizationValue)
        .find('img').trigger('click');
      var displayName = customizationValue == 'background' ? '' : 'none' ;
      _this.jQueryObj.find('.current_' + customizationValue + ' > span').text( displayName )
        .find('span').remove( );
      _this.jQueryObj.find('.tempClearOption').remove( );
    }
    else // clearing an 'outfit' is exceptional
    {
      getFlashMovie( _this.flashObjId ).resetBear( );
      _this.giftCustomizations['outfit'] = '';
      _this.giftCustomizationPrices['outfit'] = 0;
      _this.giftCustomizationDisplay['outfit'] = '';
      for ( var x in _this.outfitCustomizations )
      {
        _this.giftCustomizations[ x ] = '';
        _this.giftCustomizationPrices[ x ] = 0;
        _this.giftCustomizationDisplay[ x ] = '';
      }
      _this.jQueryObj.find('.customization:not(.bear, .background) .option').removeClass('optionSelected');
      _this.updateGiftUsage( );
    }
  };

  this.setCustomization = function( name, value, price, displayName, selectElement, skipUpdate )
  {
    if ( _this.giftName == 'beargram' && name == 'outfit' )
    {
      _this.ajax({
          action          : 'outfit',
          outfitValue     : value
        },
        function( obj ) {
          if ( obj.outfit )
          {
            _this.jQueryObj.find('.customization:not(.bear, .background) .option').removeClass('optionSelected');
            if ( selectElement )
            {
              selectElement.addClass('optionSelected');
            }
            getFlashMovie( _this.flashObjId ).resetBear( );

            for ( var x in obj.outfit )
            {
              var cName        = obj.outfit[ x ].customization_name;
              var cValue       = obj.outfit[ x ].customization_value;
              var cPrice       = obj.outfit[ x ].customization_value_price;
              var cDisplayName = obj.outfit[ x ].customization_value_description;
              var cSelect      = _this.jQueryObj.find('.customization.' + obj.outfit[ x ].customization_name + ' .option .value:contains(' + obj.outfit[ x ].customization_value + ')').parent( );
              _this.setCustomization( cName, cValue, cPrice, cDisplayName, cSelect, true );
            }

            _this.giftCustomizations['outfit'] = value;
            _this.giftCustomizationPrices['outfit'] = price >= 0 ? price : 0 ;
            _this.giftCustomizationDisplay['outfit'] = displayName;

            _this.updateGiftUsage( );
          }
          else
          {
            $.dragonAlert( obj.error, { title:'Oops!' } );
          }
        });
    }
    else
    {
      _this.giftCustomizations[ name ] = value;
      _this.giftCustomizationPrices[ name ] = price >= 0 ? price : 0 ;
      _this.giftCustomizationDisplay[ name ] = value == 'none' ? '' : displayName ;

      if ( _this.giftName == 'beargram' && _this.outfitCustomizations[ name ] )
      {
        _this.giftCustomizations['outfit'] = 'custom';
        _this.giftCustomizationPrices['outfit'] = 0;
        _this.giftCustomizationDisplay['outfit'] = 'Custom';
      }

      _this.jQueryObj.find('.customization.' + name + ' .option').removeClass('optionSelected');
      if ( selectElement )
      {
        selectElement.addClass('optionSelected');
      }

      if ( !skipUpdate )
      {
        _this.updateGiftUsage( );
      }

      if ( !_this.flashObjVisible )
      {
        _this.jQueryObj.find('.preview .text').hide( );
        $('#'+_this.flashObjId).parent( ).not(':visible').show( );
        _this.flashObjVisible = true;

        setTimeout( function(){ // slight delay so it waits for the Flash object to initialize
          eval( 'getFlashMovie("' + _this.flashObjId + '").' + name + '( "' + value + '" );' );
        }, 500 );
      }
      else
      {
        eval( 'getFlashMovie("' + _this.flashObjId + '").' + name + '( "' + value + '" );' );
      }
    }
  };


  // bind customization actions
  this.bindActions = function( )
  {
    _this.jQueryObj.find('.stepSelector span').bind('click', function(e) {
      if ( !$(this).parents('.step').hasClass('stepOn') )
      {
        var step = $(this).parents('.step');
        if ( step.hasClass('stepCreate') )
        {
          _this.gotoCreate( );
        }
        else if ( step.hasClass('stepCustomize') )
        {
          _this.gotoCustomize( );
        }
        else if ( step.hasClass('stepSend') )
        {
          _this.gotoSend( );
        }
      }
      $('div.colorPicker').hide( );
      _this.updateGiftUsage( );
      try
      {
        getFlashMovie( _this.flashObjId ).stopMusic( );
      }
      catch(e) { }
    });
    _this.jQueryObj.find('.tabsContainer .tab .text span').bind('click', function(e) {
      var tab = $(this).parents('.tab');
      if ( tab.parents('.create').length > 0 )
      {
        if ( !_this.promptUser( _this.jQueryObj.find('.create') ) )
        {
          _this.jQueryObj.find('.create .section').hide( );
        }
        else
        {
          return false;
        }
      }
      else if ( tab.parents('.customize').length > 0 )
      {
        _this.jQueryObj.find('.customize .customization, .customize .current_background').hide( );
      }
      $(this).parents('.tabsContainer').find('.tab').removeClass('tabSelected');
      tab.addClass('tabSelected');

      $( 'div.colorPicker' ).hide( );
      _this.updateGiftUsage( );
      try
      {
        getFlashMovie( _this.flashMusicObjId ).stopSound( );
      }
      catch(e) { }

      if ( tab.hasClass('tabBackground') )
      {
        _this.jQueryObj.find('.customize .background, .customize .current_background').show( );
      }
      else if ( tab.hasClass('tabPersonalMessage') )
      {
        _this.jQueryObj.find('.customize .personalMessage').show( );
        tab.find('.prompt').remove( );
      }
      else if ( tab.hasClass('tabMusic') )
      {
        _this.jQueryObj.find('.customize .music').show( );
        tab.find('.prompt').remove( );
      }
      else if ( tab.hasClass('tabPrivacy') )
      {
        _this.jQueryObj.find('.customize .privacy').show( );
        tab.find('.prompt').remove( );
      }
      // beargram only
      else if ( tab.hasClass('tabChooseBear') )
      {
        _this.jQueryObj.find('.create .chooseBear').show( );
        tab.find('.prompt').remove( );
      }
      else if ( tab.hasClass('tabPickAnOutfit') )
      {
        _this.jQueryObj.find('.create .pickAnOutfit').show( );
        tab.find('.prompt').remove( );
      }
      else if ( tab.hasClass('tabAccessories') )
      {
        _this.jQueryObj.find('.create .accessories').show( );
        tab.find('.prompt').remove( );
      }
      else if ( tab.hasClass('tabShoes') )
      {
        _this.jQueryObj.find('.create .shoes').show( );
        tab.find('.prompt').remove( );
      }

    });

    //beargram only subtabs
    _this.jQueryObj.find('.subtab span').bind('click', function(e) {
      var section = $(this).parents('.section');
      section.find('.subtab').removeClass('subtabSelected');
      section.find('.customization').hide( );
      var subtab = $(this).parent( ).addClass('subtabSelected');
      subtab.parents('.section').find('.current').hide( );
      if ( subtab.hasClass('subtabOutfit') )
      {
        subtab.parents('.section').find('.customization.outfit, .current_outfit').show( );
      }
      else if ( subtab.hasClass('subtabTop') )
      {
        subtab.parents('.section').find('.customization.top, .current_top').show( );
      }
      else if ( subtab.hasClass('subtabBottom') )
      {
        subtab.parents('.section').find('.customization.bottom, .current_bottom').show( );
      }
      else if ( subtab.hasClass('subtabHat') )
      {
        subtab.parents('.section').find('.customization.hat, .current_hat').show( );
      }
      else if ( subtab.hasClass('subtabBag') )
      {
        subtab.parents('.section').find('.customization.bag, .current_bag').show( );
      }
      else if ( subtab.hasClass('subtabJewelry') )
      {
        subtab.parents('.section').find('.customization.jewelry, .current_jewelry').show( );
      }
      else if ( subtab.hasClass('subtabGlasses') )
      {
        subtab.parents('.section').find('.customization.glasses, .current_glasses').show( );
      }
      _this.updateGiftUsage( );
    });
    //beargram only gender option
    _this.jQueryObj.find('.pickAnOutfit .sex .all').click( function(e) {
      _this.jQueryObj.find('.pickAnOutfit .sex span').removeClass('sexSelected');
      $(this).addClass('sexSelected');
      _this.jQueryObj.find('.pickAnOutfit .arrowLeft')
        .siblings('.set').text('0').end( )
        .children('.page').text('1').end( )
        .trigger('click');
    });
    _this.jQueryObj.find('.pickAnOutfit .sex .male').click( function(e) {
      _this.jQueryObj.find('.pickAnOutfit .sex span').removeClass('sexSelected');
      $(this).addClass('sexSelected');
      _this.jQueryObj.find('.pickAnOutfit .arrowLeft')
        .siblings('.set').text('male').end( )
        .children('.page').text('1').end( )
        .trigger('click');
    });
    _this.jQueryObj.find('.pickAnOutfit .sex .female').click( function(e) {
      _this.jQueryObj.find('.pickAnOutfit .sex span').removeClass('sexSelected');
      $(this).addClass('sexSelected');
      _this.jQueryObj.find('.pickAnOutfit .arrowLeft')
        .siblings('.set').text('female').end( )
        .children('.page').text('1').end( )
        .trigger('click');
    });

    _this.jQueryObj.find('.customization .arrowLeft, .customization .arrowRight').bind('click', pageCustomizations);
    _this.jQueryObj.find('.nextStep span').unbind('click').bind('click', function(e) {
      _this.nextStep( $(this).parent( ) );
    });

    function bindCustomizations( e )
    {
      var option = $(this).siblings('.value').text( );
      var customizationId = $(this).parent( ).siblings('.customizationId').text( );
      var price = $(this).parent( ).find('.price span:not(.rel)').text( );
      var displayName = $(this).parent( ).find('.name').text( );

      $(this).parent( ).siblings('.prompt').remove( );

      _this.setCustomization( customizationId, option, price, displayName, $(this).parent( ) );
    }
    _this.jQueryObj.find('.customization .option img, .customization .option .name').bind('click', bindCustomizations);

    function bindOutfitHoverTips( )
    {
      _this.jQueryObj.find('.customization.outfit .option img').each( function(i) {
        var content = $(this).siblings('.VIPGift-whatsIncluded').find('.title').remove( ).end( ).prepend('<div class="title">What\'s Included?</div>').clone( ).removeClass('hide');
        $(this).hoverTip( content );
      });
    }
    bindOutfitHoverTips( );

    function pageCustomizations( e )
    {
      var page = $(this).children('.page').text( );
      var customizationId = $(this).siblings('.customizationId').text( );
      var promptText = $(this).siblings('.prompt').text( );
      var nextStepText = $(this).parents('.customization').find('.nextStep span').text( );
      _this.ajax({
          action          : 'pageCustomizations',
          giftName        : _this.giftName,
          customizationId : customizationId,
          nextStepText    : nextStepText,
          promptText      : promptText,
          page            : page,
          per_page_custom : $(this).siblings('.per_page_custom').text( ),
          set             : $(this).siblings('.set').text( ) // beargram only, for now
        },
        function( obj ){
          if ( obj.content )
          {
            var isVisible = ( _this.jQueryObj.find('.customization.'+obj.customizationId+':visible').length > 0 );
            _this.jQueryObj.find('.customization.'+obj.customizationId).hide( ).after( obj.content ).remove( );
            isVisible ? _this.jQueryObj.find('.customization.'+obj.customizationId).show( ) : _this.jQueryObj.find('.customization.'+obj.customizationId).hide( ) ;
            _this.updateGiftUsage( );

            if ( _this.giftJSONObj.VIPMember.isVIP && _this.giftJSONObj.VIPMember.freeGiftLeft > 0 )
            {
              _this.jQueryObj.find( '.customization .option div.price' ).addClass( 'hide' );
              _this.jQueryObj.find( '.customization .option div.free' ).removeClass( 'hide' );
              _this.jQueryObj.find( '.customization .option span.price' ).html( 'FREE' );
            }

            // mark as selected if... already... selected...
            _this.jQueryObj.find('.customization.'+obj.customizationId+' .option .value').each(function( i ) {
              if ( $(this).text( ) == _this.giftCustomizations[ obj.customizationId ] )
              {
                $(this).parent( ).addClass('optionSelected');
              }
            });

            _this.jQueryObj.find('.customization.'+obj.customizationId+' .arrowLeft, .customization.'+obj.customizationId+' .arrowRight').bind('click', pageCustomizations);
            _this.jQueryObj.find('.customization.'+obj.customizationId+' .option img, .customization.'+obj.customizationId+' .option .name').bind('click', bindCustomizations);
            bindOutfitHoverTips( );

            _this.jQueryObj.find('.nextStep span').unbind('click').bind('click', function(e) {
              _this.nextStep( $(this).parent( ) );
            });
          }
          else
          {
            _this.error( obj.error );
          }
        });
    }

    _this.jQueryObj.find('.customization.personalMessage .yourMessage textarea').bind('change keyup mouseup', function(e) {
      if ( _this.giftName == 'love_note' && $(this).val( ).length > 80 )
      {
        $(this).val( $(this).val( ).substr( 0, 80 ) );
        $(this).siblings('.notice').css('color', '#F00');
      }
      else if ( $(this).val( ).length > 150 )
      {
        $(this).val( $(this).val( ).substr( 0, 150 ) );
        $(this).siblings('.notice').css('color', '#F00');
      }
      else
      {
        $(this).siblings('.notice').css('color', '#999');
      }
      _this.message = $(this).val( );
      _this.message = _this.message.replace( /[\n\r\t]/g, ' ' );
      getFlashMovie( _this.flashObjId ).setMessageText( _this.message );
      $(this).parents('.personalMessage').find('.prompt').remove( );
    });
    _this.jQueryObj.find('.customization.personalMessage .messageAnimation select').bind('change', function(e) {
      var animId = $(this).val( );
      var customizationId = $(this).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = animId;
      getFlashMovie( _this.flashObjId ).setMessageAnimation( animId );
    });
    _this.jQueryObj.find('.customization.personalMessage .font select').bind('change', function(e) {
      var fontId = $(this).val( );
      var customizationId = $(this).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = fontId;
      getFlashMovie( _this.flashObjId ).setMessageFont( fontId );
    });
    _this.jQueryObj.find('.customization.personalMessage .size select').bind('change', function(e) {
      var sizeId = $(this).val( );
      var customizationId = $(this).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = sizeId;
      getFlashMovie( _this.flashObjId ).setMessageFormatProperty( 'fontSize', sizeId );
    });
    _this.jQueryObj.find('.customization.personalMessage .messageColor .color').colorPicker( function( color, element ) {
      $(element).css('background-color', color);
      color = color.replace('#', '');
      var customizationId = $(element).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = color;
      color = '0x' + color;
      getFlashMovie( _this.flashObjId ).setMessageFormatProperty( 'fontColor', color );
    }, _this.giftJSONObj.messageFontColors );
    _this.jQueryObj.find('.customization.personalMessage .messageDropShadow input').bind('change click', function(e) {
      var val;
      $(this).filter(':checked').length > 0 ? val = $(this).val( ) : val = '' ;
      var customizationId = $(this).parent( ).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = val;
      val ? val = '0x' + val : null ;
      getFlashMovie( _this.flashObjId ).setMessageDropShadowColor( val );
    });
    _this.jQueryObj.find('.customization.personalMessage .messageDropShadow .color').colorPicker( function( color, element ) {
      $(element).css('background-color', color);
      color = color.replace('#', '');
      _this.jQueryObj.find('.customization.personalMessage .messageDropShadow input.dropShadowOn').val( color );
      $(element).siblings('label').children('input').val([ color ]).trigger('change');
    }, _this.giftJSONObj.messageDropShadowColors );
    _this.jQueryObj.find('.customization.personalMessage .messageBackground input').bind('change click', function( e ){
      var val;
      $(this).filter(':checked').length > 0 ? val = $(this).val( ) : val = '' ;
      var customizationId = $(this).parent( ).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = val;
      val ? val = '0x' + val : null ;
      getFlashMovie( _this.flashObjId ).setMessageBackgroundColor( val );
    });
    _this.jQueryObj.find('.customization.personalMessage .messageBackground .color').colorPicker( function( color, element ) {
      $(element).css('background-color', color);
      color = color.replace('#', '');
      _this.jQueryObj.find('.customization.personalMessage .messageBackground input.backgroundOn').val( color );
      $(element).siblings('label').children('input').val([ color ]).trigger('change');
    }, _this.giftJSONObj.messageBackgroundColors );
    _this.jQueryObj.find('.customization.personalMessage .previewBtn').bind('click', function(e) {
      _this.jQueryObj.find('.customization.personalMessage .messageAnimation select').trigger('change');
      getFlashMovie( _this.flashObjId ).updateMessage( );
      getFlashMovie( _this.flashObjId ).setMessageAnimation( _this.jQueryObj.find('.customization.personalMessage .messageAnimation select').val( ) );
    });
    _this.jQueryObj.find('.customization.personalMessage .note select').bind('change click', function(e) {
      $('#VIPGift-customNote').slayDragon( );
      var customizationId = $(this).siblings('.customizationId').text( );
      var noteVal = $(this).val( );
      if ( noteVal == 'customNote' )
      {
        var customNotePopup = $('<div />').appendTo('body')
          .dragonDrop({
            curtain : false,
            type    : 'window',
            title   : 'Create Your Own Poem',
            content : $('<textarea>' + _this.customNote + '</textarea><div class="notice">Message cannot be longer than 2000 characters</div><img src="' + IMAGE_URL2 + 'images/buttons/submit_lg.gif" />')
          }).attr('id', 'VIPGift-customNote').centerOnScreen( );

        getFlashMovie( _this.flashObjId ).setNoteText( _this.customNote );
        getFlashMovie( _this.flashObjId ).updateNote( );

        customNotePopup.find('textarea').bind('change keyup mouseup', function(e) {
          if ( $(this).val( ).length > 2000 )
          {
            $(this).val( $(this).val( ).substr( 0, 2000 ) );
            $(this).siblings('.notice').css('color', '#F00');
          }
          else
          {
            $(this).siblings('.notice').css('color', '#999');
          }
          _this.customNote = $(this).val( );
          getFlashMovie( _this.flashObjId ).setNoteText( _this.customNote );
          getFlashMovie( _this.flashObjId ).updateNote( );
        });
        customNotePopup.find('.dragonContent img').bind('click', function(e) {
          _this.giftCustomizations[ customizationId ] = 'customNote';
          $('#VIPGift-customNote').slayDragon( );
        });
      }
      else
      {
        var noteText = $(this).find('option:selected').text( );
        getFlashMovie( _this.flashObjId ).setNoteData( noteText );
        getFlashMovie( _this.flashObjId ).updateNote( );
        _this.giftCustomizations[ customizationId ] = noteVal;
      }
    });
    _this.jQueryObj.find('.customization.personalMessage .noteFontType select').bind('change', function(e) {
      var fontId = $(this).val( );
      var customizationId = $(this).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = fontId;
      getFlashMovie( _this.flashObjId ).setNoteFont( fontId );
    });
    _this.jQueryObj.find('.customization.personalMessage .noteFontSize select').bind('change', function(e) {
      var sizeId = $(this).val( );
      var customizationId = $(this).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = sizeId;
      getFlashMovie( _this.flashObjId ).setNoteFormatProperty( 'fontSize', sizeId );
    });
    _this.jQueryObj.find('.customization.personalMessage .noteColor .color').colorPicker( function( color, element ) {
      $(element).css('background-color', color);
      var customizationId = $(element).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = color.replace( '#', '' );
      color = color.replace( '#', '0x' );
      getFlashMovie( _this.flashObjId ).setNoteFormatProperty( 'fontColor', color );
    }, _this.giftJSONObj.noteColors );
    _this.jQueryObj.find('.customization.personalMessage .stamp select').bind('change', function(e) {
      var stampId = $(this).val( );
      var customizationId = $(this).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = stampId;
      getFlashMovie( _this.flashObjId ).stamp( stampId );
    });

    _this.jQueryObj.find('.customization.music .addMusic input').bind('click change', function(e) {
      var elem = $(this).parents('.music').find('.selectAGenre select, .selectASong select');
      var customizationId = _this.jQueryObj.find('.customization.music .selectASong .customizationId').text( );
      if ( $(this).val( ) == 1 )
      {
        elem.attr('disabled', '');
        var musicVal = _this.jQueryObj.find('.customization.music .selectASong select').val( );
        _this.giftCustomizations[ customizationId ] = musicVal;
      }
      else
      {
        elem.attr('disabled', true);
        getFlashMovie( _this.flashMusicObjId ).stopSound( );
        _this.giftCustomizations[ customizationId ] = '';
      }
    });
    /**
     * Since setting <option />s to "disabled" isn't supported by IE, we'll have to come up with our own
     * way of pulling this off. We'll first clone the <select /> that contains all of the song options,
     * which we can then use to filter and populate the visible <select /> based on the genre that was chosen.
     */
    _this.musicSelect = _this.jQueryObj.find('.customization.music .selectASong select').clone( );
    _this.jQueryObj.find('.customization.music .selectAGenre select').bind('change', function(e) {
      var genre = $(this).val( );
      var options = genre != 0 ? _this.musicSelect.find('option.'+genre) : _this.musicSelect.find('option') ;
      $(this).parents('.music').find('.selectASong select')
        .find('option').remove( ).end( )
        .append( options.clone( ) );
      _this.jQueryObj.find('.customization.music .selectASong select').trigger('change');
    });
    _this.jQueryObj.find('.customization.music .selectASong select').bind('change', function(e) {
      var customizationId = $(this).siblings('.customizationId').text( );
      _this.giftCustomizations[ customizationId ] = $(this).val( );
      // update flashvars for music preview obj
      var flashvars = $('#'+_this.flashMusicObjId+' param[name=flashvars]').attr('value');
      flashvars = flashvars.replace( /defaultVal=\w+|defaultVal=/gi, 'defaultVal=' + $(this).val( ) );
      $('#'+_this.flashMusicObjId+' param[name=flashvars]').attr('value', flashvars);
    });
    _this.jQueryObj.find('.customization.music .previewSong img').bind('click', function(e) {
      var val = $(this).parents('.music').find('.selectASong select').val( );
      getFlashMovie( _this.flashMusicObjId ).loadAndPlay( val );
    });

    _this.jQueryObj.find('.customization.privacy input').bind('change', function(e) {
      var val = $(this).val( );
      if ( val == 'private' )
      {
        _this.isPrivate = true;
        _this.isAnonymous = false;
      }
      else if ( val == 'anonymous' )
      {
        _this.isPrivate = false;
        _this.isAnonymous = true;
      }
      else
      {
        _this.isPrivate = _this.isAnonymous = false;
      }
    });

    _this.jQueryObj.find('.send img.previewGift').bind('click', function(e) {
      $('#VIPGift-buyAlert').slayDragon( );
      var musicCustomizationId = _this.jQueryObj.find('.customization.music .selectASong .customizationId').text( );
      getFlashMovie( _this.flashObjId ).setMusic( _this.giftCustomizations[ musicCustomizationId ] );
      getFlashMovie( _this.flashObjId ).userPreview( );
    });
    _this.jQueryObj.find('.send img.giveGift').bind('click', function(e) {
      if ( _this.giftJSONObj.captcha )  // has captcha
      {
        if ( $( '#VIPGifts-wrapper .send .captchaArea' ).hasClass( 'hide' ) ) // show captcha area
        {
          $( '#VIPGifts-wrapper .send .text' ).addClass( 'hide' );
          $( '#VIPGifts-wrapper img.previewGift' ).addClass( 'hide' );
          $( '#VIPGifts-wrapper .send .buttons' ).addClass( 'captchaBtn' );
          $( '#VIPGifts-wrapper .send .captchaArea' ).removeClass( 'hide' );
          $( '#recaptcha_response_field' ).focus( );
          return false;
        }
        else  // check captcha value
        {
          var captchaStr = $( '#VIPGifts-wrapper #recaptcha_response_field' ).val( );
          var captcharChallenge = Recaptcha.get_challenge( );
          
          _this.ajax({ action : 'captcha', recaptcha_response_field : captchaStr, recaptcha_challenge_field : captcharChallenge }, function( obj ){
            if ( obj.success )  // right captcha confirmed
            {
              $( '#recaptcha_instructions_error' ).hide( );
              $( '#VIPGifts-wrapper .send .captchaArea' ).addClass( 'hide' );
              $( '#VIPGifts-wrapper .send .text' ).removeClass( 'hide' );
              $( '#VIPGifts-wrapper img.previewGift' ).removeClass( 'hide' );
              $( '#VIPGifts-wrapper .send .buttons' ).removeClass( 'captchaBtn' );
              _this.giftJSONObj.captcha = false;
              _this.confirmGive( );
            }
            else   // wrong captcha
            {
              $( '#recaptcha_instructions_error' ).show( );
              Recaptcha.reload( );
              return false;
            }
          });
        }
      }
      else    // has no captcha
      {
        _this.confirmGive( );
      }
    });
  };

  // confirm give gift
  this.confirmGive = function( )
  {
    $('#VIPGift-buyAlert').slayDragon( );
    if ( !_this.promptUser( _this.jQueryObj.find('.customize'), _this.gotoCustomize, true ) )
    {
      _this.give( );
    }
    return false;
  };

  // utility methods
  this.ajax = function( data, successFunc )
  {
    var url;
    if ( MyYearbook.currentServiceName == 'VIP' )
    {
      url = '/gifts/give';
    }
    else if ( MyYearbook.currentServiceName == 'www' )
    {
      url = '/apps/comet/vipGiftGive';
    }
    else
    {
      url = '/comet/vipGiftGive';
    }
    $.ajax({
      url      : url,
      type     : 'POST',
      data     : data,
      dataType : 'json',
      success  : function( obj )
      {
        if ( obj.isInMaintenance )
        {
          _this.displayMaintenance( );
        }
        else if ( $.isFunction( successFunc ) )
        {
          successFunc( obj );
        }
      },
      error : function( obj, textStatus, errorThrown )
      {
        _this.error( );
      }
    });
  };

  this.displayMaintenance = function( )
  {
    $.evalWithStatusComplete( true );
    var content = 'VIP Gifts is currently undergoing maintenance.  Please check back soon!';
    var alertBox = $.dragonAlert( content, { title:'VIP Gifts Maintenance' } );
    alertBox.attr('id', 'VIPGift-maintenance');
  };

  this.error = function( errorMsg )
  {
    if ( !errorMsg )
    {
      errorMsg = 'An unknown error has occurred. Please try again.';
    }
    $.evalWithStatusComplete( true );
    this.close( );
    $.dragonAlert( errorMsg, {title:'Oops!'});
  };

}

/**
 * VIPGiftOpen
 *
 * Creates a JavaScript popup for viewing the selected gift.
 */
function VIPGiftOpen( memberGiftId, prevGiftFunc, nextGiftFunc )
{
  // constructor actions
  var _this = this;
  this.jQueryObj = $('#VIPGiftOpen');
  this.jQueryObj.slayDragon( );
  this.flashObjId = 'VIPGiftOpenObj';
  this.prevGiftFunc = prevGiftFunc;
  this.nextGiftFunc = nextGiftFunc;
  IMAGE_URL.charAt(-1) != '/' ? IMAGE_URL2 = IMAGE_URL+'/' : IMAGE_URL2 = IMAGE_URL ;

  $.evalWithStatus( function( ){
    var ajaxObj = { action : 'build', memberGiftId : memberGiftId };
    _this.ajax( ajaxObj, function( obj ){
      $.evalWithStatusComplete( true );
      if ( obj.success )
      {
        var title = '';
        obj.givenByProfileLink ? title += '<a href="' + obj.givenByProfileLink + '">' + obj.givenByName + '</a>' : title += obj.givenByName ;
        title += ' bought ';
        obj.givenToProfileLink ? title += '<a href="' + obj.givenToProfileLink + '">' + obj.givenToName + '</a>' : title += obj.givenToName ;
        title += ' a <strong>VIP Gift of ' + obj.giftDisplayName + '</strong>';

        var content = $('<div><div class="gift">' + obj.flashObject + '</div></div>');

        if ( _this.prevGiftFunc )
        {
          var prevGiftObj = $('<div class="arrowLeft"><div></div></div>').bind('click', _this.prevGiftFunc);
          content.prepend( prevGiftObj );
        }
        if ( _this.nextGiftFunc )
        {
          var nextGiftObj = $('<div class="arrowRight"><div></div></div>').bind('click', _this.nextGiftFunc);
          content.prepend( nextGiftObj );
        }

        if ( obj.showGiveGift )
        {
          var giftBackImg = obj.showGiveGiftBack ? 'btn_gift_back.gif' : 'give_vip_gift_small.gif' ;
          content.append('<img src="' + IMAGE_URL2 + 'images/buttons/' + giftBackImg + '" />')
            .find('img').bind('click', function(e) {
              _this.close( );
              new VIPGiftGive( obj.givenBy );
            });
        }

        if ( obj.showEmbed )
        {
          content.append('<div class="embed"><strong>Embed Code:</strong> <input class="copy" type="text" value="" /></div>')
            .find('input').val( obj.flashCode );
        }

        _this.jQueryObj = $('<div id="VIPGiftOpen" />').appendTo('body').dragonDrop({
          type           : 'window',
          curtain        : true,
          title          : title,
          content        : content
        });
        _this.jQueryObj.find('.titleBar').append( $('<span class="date">Given on ' + obj.giftDate + '</span>') );

        initCopyTextareas( ); // from site.js
        eval( obj.flashScript );
        if ( typeof Meebo != "undefined" && $.isFunction( Meebo.registerFlashObj ) )
        {
          Meebo.registerFlashObj( $('#'+_this.flashObjId).get(0) );
        }
      }
      else
      {
        _this.error( obj.error );
      }
    });
  });

  // methods
  this.close = function( )
  {
    this.jQueryObj.slayDragon( null, true );
  };

  // utility methods
  this.ajax = function( data, successFunc )
  {
    var url;
    if ( MyYearbook.currentServiceName == 'VIP' )
    {
      url = '/gifts/open';
    }
    else if ( MyYearbook.currentServiceName == 'www' )
    {
      url = '/apps/comet/vipGiftOpen';
    }
    else
    {
      url = '/comet/vipGiftOpen';
    }
    $.ajax({
      url      : url,
      type     : 'POST',
      data     : data,
      dataType : 'json',
      success  : function( obj )
      {
        if ( obj.isInMaintenance )
        {
          _this.displayMaintenance( );
        }
        else if ( $.isFunction( successFunc ) )
        {
          successFunc( obj );
        }
      },
      error : function( obj, textStatus, errorThrown )
      {
        _this.error( );
      }
    });
  };

  this.displayMaintenance = function( )
  {
    $.evalWithStatusComplete( true );
    var content = 'VIP Gifts is currently undergoing maintenance.  Please check back soon!';
    var alertBox = $.dragonAlert( content, { title:'VIP Gifts Maintenance' } );
    alertBox.attr('id', 'VIPGift-maintenance');
  };

  this.error = function( errorMsg )
  {
    if ( !errorMsg )
    {
      errorMsg = 'An unknown error has occurred. Please try again.';
    }
    $.evalWithStatusComplete( true );
    this.close( );
    $.dragonAlert( errorMsg, {title:'Oops!'});
  };

}
