var modcloth = (function(mc, $){
  // var mc = parent = parent || {};

  mc.btb = {
    /*
     * Update page attributes for IE6
     * replace pngs with gifs
    */
    categoryLoaded : function(){
      if($.browser.msie&&parseFloat($.browser.version) < 7) {
        $('.yes').attr('src', '/images/btb-i-voted-pick.gif');
        $('.no').attr('src', '/images/btb-i-voted-skip.gif');
        $('#btb-logo img').attr('src', '/images/btb-logo-transparent.gif');
        $('.thumbnail-prev').attr('src', '/images/quicklook/images-arrow-up.gif');
        $('.thumbnail-next').attr('src', '/images/quicklook/images-arrow-down.gif');
        $('.btb-badge').attr('src', '/images/btb/btb-pick-badge.gif');
      }
      $('.product_cat_view').ieOverlayHover('.quickvote', 70);
    },
    /*
     * cross-browser placeholder behavior for comment textarea
    */
    comments : function(options){
      $('textarea.placeholder').one_time_placeholder(options);
    },
    /*
     * add tooltips to tabs and comment examples
    */
    tooltips : function(options){
      $('.tabs li[title]').tool_bubble({'class':'tool btb','tag':'span'});
      $('#btb-content a.example').disable_click().tool_bubble({'class':'tool btb comment','offset':[-8,10],'tag':'span'});
      $('#quicklook a.example').disable_click().tool_bubble({'class':'tool btb comment','offset':[-8,10],'tag':'span','animateIE':false});
    },
    quickvoteTooltips : function(){
      if($.browser.msie && parseFloat($.browser.version) < 7) {
        // IE6 positioning is whack
      } else {
        $('#btb-modules a[data-image]').tool_bubble({'appendToBody':true,'offset':[-12,0],'carat':false,'class':'quicklook-tool'}).click(function(){
          $('.quicklook-tool').tool_bubble_destroy(false);
        });
      }
    },
    showInHeader : function(target, content, options, fn){
      if($.isFunction(options)) {
        // options and callback are optional
        fn = options;
        options = headerDefaults;
      } else {
        // pull in defaults
        options = $.extend({}, headerDefaults, options);
      }
      if (options.animated) setTimeout(function(){ _private.show(target, content, options, fn) }, 300);
      else _private.show(target, content, options, fn)
    },
    removeOnClick : function(actors, targets){
      // $(actors).bind('click', function(e){
      //   e.preventDefault();
      //   $(targets).hide().remove();
      // });
    }
  };

  var headerDefaults = {
    'animated':true,
    'animatedContent':'.animated',
    'delayedItems':'.delay',
    'delayedFadeIn':300,
    'scrollers':'.next, .prev, .btb-pick.logged-in, .btb-skip.logged-in'
  };

  var _private = {
    /*
     * animate content into Be the Buyer header module
    */
    show : function(target, content, options, fn){
      target = $(target);
      if (target.length != 1) throw 'MC.btb.showInHeader() should target a single container element';

      target.html($(content));
      $(options.animatedContent+','+options.delayedItems, target).hide();
      modcloth.btb.categoryLoaded();

      if (options.animated) {
        _private.animateIn($(options.animatedContent, target), options, function(){
          $(options.delayedItems, target).fadeIn(options.delayedFadeIn);
          if(fn) fn();
        });
      } else {
        $(options.animatedContent, target).show();
        $(options.delayedItems, target).show();
        if(fn) fn();
      }

      $(options.scrollers, target).bind('click', function(e){
        e.preventDefault();
        var slow = ($(this).attr('data-slow-fade')) ? true : false;
        _private.hide(target, $(this).attr('data-dir') || 'right', $.extend({'slow':slow}, options));
      });
    },
    /*
     * animate content out of BtB header module
    */
    hide : function(target, dir, options){
      // hide the quicklook window and remove it from DOM
      if(typeof(dir)=='object'){
        options = dir;
        dir = 'right';
      }

      options = $.extend({}, headerDefaults, options);
      target = $(target);

      $(options.scrollers, target).kill_tool_bubble({'class':'quicklook-tool'});

      _private._setState(dir);

      var time = (options.slow) ? 800 : 400;
      if ($.browser.msie) time = 600;

      // only hide these. removing them prevents live handlers from firing in IE.
      $(options.delayedItems, target).hide();
      $(options.animatedContent, target).fadeDestroy(time, dir, '1200');
    },
    /*
     * used by _private.show();
    */
    animateIn : function(target, options, callback){
      target.fadeIn(100, callback);
    },
    _setState : function(dir){
      return _private._state = dir;
    },
    _getState : function(){
      return _private._state || null;
    },
    _clearState : function(){
      delete _private._state;
    }
  };

  // TODO: move this out of BTB js so category quicklook can use
  /* ieOverlayHover

    IE does not like CSS. Even though :hover covers this behavior in
    other browsers, this is needed for consistent behavior in IE6-8.

  */
  $.fn.ieOverlayHover = function(target, opacity){
    if(! $.browser.msie) return this;

    this.unbind('.ieOpacity');

    this.bind('mouseenter.ieOpacity', function(){
      el = $(this).find(target);
      el.show();
      el.css('filter','alpha(opacity='+opacity+')');
      el.bind('mouseenter.ieOpacity', function(){
        $(this).css('filter','alpha(opacity=100)');
      });
      el.bind('mouseleave.ieOpacity', function(){
        $(this).css('filter','alpha(opacity='+opacity+')');
      });
    });

    this.bind('mouseleave.ieOpacity', function(){
      el = $(this).find(target);
      el.unbind('.ieOpacity');
      el.hide();
    });

    return this;
  };

  return mc;

}(modcloth || {}, jQuery));

function pinkify_site()
{
  $('img#modcloth_logo').attr('src', '/images/btb-modcloth-logo-pink.png');
}

function btbLoaded()
{
  $('#total-comment_count_showing').html(''+$('.comments_main .user_comment').size()+'');

  $('button.btb-action').mouseup(function(){
    $(this).addClass('selected');
  });

  initiate_text_area();
  loadCarousels();

  if ($(".rec-products").length > 0) {
    $(".rec-products").jCarouselLite({
      btnNext: ".rec-products-next",
      btnPrev: ".rec-products-prev",
      visible: 7,
      start: 0,
      circular: false,
      hover: true,
      speed: 'auto',
      singleSpeed: 200,
      offset: $(".rec-products").find('ul:first').offset().left
    });
  }

  var msie6 = $.browser == 'msie' && $.browser.version < 7;

            if (!msie6) {
              var top = $('#comments-right').offset().top - parseFloat($('#comments-right').css('margin-top').replace(/auto/, 0));
              bottom = top
              $(window).scroll(function (event) {
                // what the y position of the scroll is
                var y = $(this).scrollTop();
                if($('#comments-left').height()>600)
                  bottom=top+$('#comments-left').height()-300;
                // whether that's below the form
                if (y >= top && $('#comments-left').height()>600) {
                  if(y > bottom && $('#comments-left').height()>600)
                  {
                      $('#comments-right').removeClass('fixed');
                      $('#comments-right').addClass('relative');
                      $('#comments-right').css('top', ''+($('#comments-left').height()-350)+'px');
                  }
                  else{
                      $('#comments-right').removeClass('relative');
                    if($.browser.msie&&$.browser.version > 7.9 || !$.browser.msie){
                          $('#commentWrapper').css('position', 'absolute');
                          $('#commentWrapper').css('left', '575px');
                      }
                      $('#comments-right').css('top', '0px');
                      $('#comments-right').addClass('fixed');
                  }
                } else {
                  // otherwise remove it
                  $('#comments-right').removeClass('relative');
                  $('#comments-right').removeClass('fixed');
                }
              });
            }


    if($.browser.msie&&$.browser.version < 7){

      $(".susan-says-arrow").attr("src", "/images/btb-comment.jpg");
      $("#btb_badge").attr("src", "/images/btb-badge.gif");

    }


  $('#comment_not_logged').fancyZoom({width:270});
  $('#skip_it_not_logged').fancyZoom({width:270});
    $('#more-questions-link').fancyZoom({width:300});
    $('#ask-modcloth-link').fancyZoom({width:300});
    $('#add-to-site-link').fancyZoom();

    activate_sharethis_menu();

  if(document.location.hash=="#kaboodle")
  {
    document.location.hash="#";
    share_kaboodle(document);
  }
  var share_using = gup('share_using');
  if(share_using == 'polyvore')
    share_polyvore(document);
}

function initiate_text_area() {
  $("textarea#your-comment").focus(function() {

    var text = $(this).val();
    $(this).attr("class", "clicked-in");

    if(text=="Whatever you write, please keep it polite!") {

      $(this).val("");

    }
  });
  $("textarea#your-comment-popup").focus(function() {

    var text = $(this).val();
    $(this).attr("class", "clicked-in");

    if(text=="Whatever you write, please keep it polite!") {

      $(this).val("");

    }
  });
}

function openShare(site, id)
{
  if(typeof(share_u)=='undefined') share_u=encodeURIComponent(addslashes(location.href));

    if(typeof(share_t)=='undefined') share_t=encodeURIComponent(document.title);

  switch(site)
  {
  case 'facebook':
    url= 'http://www.facebook.com/sharer.php?u='+encoded_u+'&t='+share_t;
      window.open(url,'sharer','toolbar=0,status=0,width=626,height=436,scrollbars=1');
    break;
  case 'twitter':
    url='http://twitter.com/home?status='+encoded_u+' (ModCloth)';
      window.open(url,'twitter','toolbar=0,status=0,width=800,height=650,scrollbars=1');
      break;
    case 'email':
    window.location = 'http://' +window.location.host + '/storefront/products/tell_a_friend?product_id='+id+'';
    break;
  }
}

function validatePopupCommentForm(){

  if($('#leave_comment #your-comment-popup').val() == "" || $('#leave_comment #your-comment-popup').val() == "Whatever you write, please keep it polite!"){
    $.jGrowl("Please enter a comment and submit", { life: 7000, theme: 'error_growl', header: 'Comment Error' });
    return false;
  }


  return true;
}

function notify_me(){
   $('#notify_name').removeClass('error');
   $('#notify_email').removeClass('error');
   var re = new RegExp(/(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/);

   if ($("#notify_email").val() == "") {
     $('#notify_email').addClass('error');
     $("#notification-error").html("Please fill in the highlighted field(s) to be notified!");
     return false;
   } else {
     if ($("#notify_email").val().match(re)) {
     }
     else {
       $('#notify_email').addClass('error');
       $("#notification-error").html("Email Address is Invalid. Please Re-enter");
       return false;
     }
   }
   $('#ajax-indicator').show();
   $('#submit_notify_button').submit();
}

$('#btb-notify.btb-action').mouseover(function(){
   $('#notification-popup').fadeIn("slow")
})

