/*!
 * BloomBox Social Networking and UGC Toolkit
 * Copyright 2006-2010, Mint Digital Limited, All rights reserved.
 */

/*jslint  eqeqeq:   true,
          immed:    false,
          newcap:   true,
          nomen:    false,
          onevar:   true,
          plusplus: false,
          undef:    true,
          white:    false */
/*global  window, alert, confirm, setTimeout, setInterval, BB, $,
          Lightbox */



/*** Forms ***/

$(function(){
  // Auto-focus first form element. Avoid common forms, like search.
  $('body:not(.searches) div.main form input:visible:first').focus();

  /*** Users > Account payment ***/
  $('#payment_account_ccn').placeholder();
});

/*** Lightboxes ***/

window.Lightbox = {};

Lightbox.attachBehaviors = function(){
  // Attach lightbox behaviors
  $([
    'a.signin, a.signup',       // sessions/new, users/new
    '.get-app a, a.get-app',    // mobile_applications/new
    'a.new-handset-interest',   // handset_interests/new
    'div#promo-greeting a',     // /queue
    'div#checkout-form h4 a',   // checkout
    'div#purchase-form ol.payment-method li.security span.info a'
                                // purchases/new
  ].join(',')).openInLightbox();
};
Lightbox.showLoading = function(){
  $('#cboxWrapper').css(
    'background',
    'transparent url(/images/content-items/loading.gif) center center no-repeat'
  );
};
Lightbox.hideLoading = function(){
  $('#cboxWrapper').css('background', 'transparent');
};

$(Lightbox.attachBehaviors); // Run when DOM is ready

/*** Lightboxes > Triggers ***/

Lightbox.openSignup = function(){
  $('a.signup:first').click();
};
Lightbox.openSignin = function(){
  $('a.signin:first').click();
};
Lightbox.openDownloadApp = function(){
  $('<a href="/mobile_applications/download"></a>').openInLightbox().click();
};
Lightbox.openPurchaseConfirmation = function(url) {
  $('<a href="' + url + '"></a>').openInLightbox().click();
};
Lightbox.reloadPage = function() {
  window.location.reload();
};

/*** Lightboxes > Handlers ***/

Lightbox.handlers = {
  session_created: function(){ window.location.reload(); },
  user_created: function(){ window.location.reload(); },
  create_new_user: function(e, email) {
    $('<a href="/users/new?email=' + (email || '') + '"></a>')
      .openInLightbox().click();
  }
};

$().bind('cbox_open', Lightbox.showLoading);
$().bind('cbox_complete', Lightbox.showLoading); // Re-positions bg image
$().bind('session_created', Lightbox.handlers.session_created);
$().bind('user_created', Lightbox.handlers.user_created);
$().bind('create_new_user', Lightbox.handlers.create_new_user);

/*** Lightboxes > ColorBox ***/

// $.fn.colorbox.settings.transition = (
//   (ieMajorVersion !== undefined) ? 'none' : 'elastic'
// );
$.fn.colorbox.settings.transition = 'none';

/*** Following a brand ***/

function FollowBrand(form){
  this.$form = $(form);
  this.setupActionListener();
}
FollowBrand.prototype.act = function(data){
  // If we are being passed data, it is from an attempt
  // to log in or sign up, and that data should be used
  // to replace the user nav.

  var _this = this,
      json, originalRequest;

  if (data) {
    json = $.toJSON(data);
    $('div.user-nav').replaceWith(json.html);
  }

  originalRequest = {
    // Cache for re-sending request after form is replaced with "Unfollow"
    url:  _this.$form.attr('action'),
    type: _this.$form.attr('method'),
    data: _this.$form.serialize()
  };
  this.$form.children('input.follow-button.follow').hide().after('<p class="loading">Following...</p>');
  this.$form.children('input.follow-button.unfollow').hide().after('<p class="loading">Unfollowing...</p>');
  this.$form.css('background', 'none');

  function requestFollow(){
    $.ajax({
      url:      originalRequest.url,
      type:     originalRequest.type,
      data:     originalRequest.data,
      dataType: 'json',
      success: function(data, status){
        var $newForm, $counters, $newCounters;

        _this.$form.children('input.follow-button').next('p.loading').hide();
        if($('body#users-account-follows').length>0){
          _this.$form.parent('li').hide('fast');
        }else{
          $newForm = $(data.button.toString());
          _this.$form.after($newForm).remove();
          _this.$form = $newForm;
          _this.setupActionListener();

          if($('#queue-module')[0]){
            $counters     = $('#queue-module .title-bar dl');
            $newCounters  = $(data.queue_counters);
            $counters.replaceWith($newCounters);
          }

          if(data.onSuccess){ Lightbox[data.onSuccess](); }
        }
      },
      error: function(obj, status, error){
        if (obj.status === 401) {
          /*
          SignUpForm.openLightBox({
            message:'Create a FREE account to follow "'+$('div.main h2').text()+'"',
            success: [_this.act, _this]
          })
          */
          Lightbox.openSignin(); // TODO: Build a way to pass header text
          $().unbind('session_created', Lightbox.handlers.session_created);
              // When user logs in, don't refresh immediately; allow browser
              // to re-request follow.
        } else {
          // alert('Sorry, there was a problem with following this brand; please try again later.');
            // Disabled alert because an "error" occurs whenever a refresh
            // happens while a XHR request is in progress. This happens when
            // the window refreshes after a re-follow request is sent.
          if(window.console && window.console.log){
            window.console.log( 'Error while following brand.' );
          }
        }
      }
    });
  }

  // If user signs in, re-request for that account
  // $().bind('session_created', requestFollow);
  $().bind('session_created', function(){
    requestFollow();
    Lightbox.handlers.session_created();
  });

  // If user didn't sign in, don't wait for its event
  $().bind('cbox_closed', function(){
    $().unbind('session_created', requestFollow);
  });

  // Initial request
  requestFollow();
};
FollowBrand.prototype.setupActionListener = function(){
  var _this = this;
  this.$form.submit(function(ev){
    _this.act();
    ev.preventDefault();
  });
};

$(function(){
  $('form.follow-button').each(function() { new FollowBrand(this); });
});

function PurchaseItem(link){
  this.$link = $(link);
  this.$link.openInLightbox();
}

$(function(){
  $('body.payment a.subscribe-button, body.payment a.rent-button').
    each(function(){ new PurchaseItem(this); });
  $('a.share-button').each(function(){
    $(this).openInLightbox();
  });
  $('form.share').openWithIframeLayout();
});

/*** Shareables ***/

/*
// TODO: Remove? Disabled because this doesn't look like it's in use.
function ShareableItem(link){
  this.link = $(link);
  if ($('#new-session')[0]) { this.setupSignInListener(); }
}
ShareableItem.prototype.setupSignInListener = function(){
  var _this = this;
  this.link.click(function(ev){
    $.ajax({
      url: _this.link.attr('href'),
      type: 'get',
      dataType: 'script',
      success: function(){window.location = _this.link.attr('href')},
      error: function(obj, status, error){
        if (obj.status == 401) {
          SignUpForm.openLightBox({
            message:'Create a FREE account to share an item',
            success: function(){window.location = _this.link.attr('href')}
          });
        } else {
          alert('Sorry, there was a problem sharing this item; please try again later.');
        }
      }
    });
    ev.preventDefault();
  });
}
$(function(){
  $('.shareable-button').each(function() { new ShareableItem(this) });
});
*/

/*** Misc ***/

$.fn.brandFooterControl = function() {
  return this.each(function() {
    var self = $(this),
        callback = function() {
          self.find('div#column-left, div#meta-availability').slideToggle();
          $(this).html($(this).html() === 'Close' ? 'Open' : 'Close');
          return false;
        };

    self.find('div.hide-button a').click(callback);
  });
};

// get a parameter from a url
$.fn.getParamFromUrl = function(param, url){
  param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex   = new RegExp("[\\?&]" + param + "=([^&#]*)"),
      results = regex.exec(url);
  return !!results ? results[1] : '';
};

$(function(){
  // Hide div.notice automatically
  setTimeout(function(){ $('div.notice').fadeOut(); }, 4000);

  // Add `text-overflow` CSS behavior to Firefox
  $('div.sidebar ul.link-grid li').ellipsis();

  $('#phone_number-1').autotab({ target: 'phone_number-2', format: 'numeric' });
  $('#phone_number-2').autotab({ target: 'phone_number-3', format: 'numeric', previous: 'phone_number-1' });
  $('#phone_number-3').autotab({ previous: 'phone_number-2', format: 'numeric' });

  $('div#brand-meta-wrap').brandFooterControl();

  $('form.purchase-form').submit(function(e){
    $(this).find('input[type="submit"]').attr('disabled','disabled').parent('span').addClass('disabled');
  });
});
