// Make any link with class=post submit via ajax post.
function setupPostLinks(){
  $('a.post').removeClass("post").click(function(event) {
    event.preventDefault();

    // Should probably make this more generic
    var params = {};
    if($(this).attr("data-popup")) params.popup = true;

    $.post(this.href, params, function(){}, 'script');
  })
}

function setupPrintLinks(){
  $('a.print').click(function(event) {
    window.print();
    event.preventDefault();
  });
}

function ajaxifyPagination(){
  $('.pagination a').unbind('click').click(function(event) {
    event.preventDefault();
    $.get(this.href, {}, function(){}, 'script');
  })
}

function reveal() {
  $("div[data-content_id]").each(function(){
    var id = $(this).attr("data-content_id");
    var p = $(this).offset();
    var mask = $('<div>').addClass("contentMask").css({left: p.left, top: p.top, width: $(this).width(), height: $(this).height() }).appendTo($('body'))
    mask.click(function(){
      window.location = "/admin/content/" + id + "/edit"
    });
  });
}

(function($) {
  $.fn.enableCheckboxRangeSelection = function() {
    var lastCheckbox = null;
    var $spec = this;
    $spec.bind("click", function(e) {
      if (lastCheckbox != null && e.shiftKey) {
        $spec.slice(
          Math.min($spec.index(lastCheckbox), $spec.index(e.target)),
          Math.max($spec.index(lastCheckbox), $spec.index(e.target)) + 1
        ).attr({checked: e.target.checked ? "checked" : ""});
      }
      lastCheckbox = e.target;
    });
    return $spec;
  };

  // (Un)Select a product, making the product image higlighted (the
  // class toggle) and checking the hidden checkbox
  $.fn.toggleEm = function() {
    return this.each(function() {
      checkbox = $(this).toggleClass('selected').parents('ul').find('li.selector input');
      checkbox.attr('checked', !checkbox.attr('checked'));
    });
  };

  $.fn.insertAtCaret = function (myValue) {
    return this.each(function(){
      //IE support
      if (document.selection) {
        this.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
      }
      //MOZILLA / NETSCAPE support
      else if (this.selectionStart || this.selectionStart == '0') {
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        var scrollTop = this.scrollTop;
        this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
        this.focus();
        this.selectionStart = startPos + myValue.length;
        this.selectionEnd = startPos + myValue.length;
        this.scrollTop = scrollTop;
      } else {
        this.value += myValue;
        this.focus();
      }
    });
  };

  // From http://github.com/brandonaaron/jquery-outerhtml
  $.fn.outerHTML = function() {
    return $('<div>').append( this.eq(0).clone() ).html();
  };

})(jQuery);

function trackMerchantClick(merchant) {
  try {
    pageTracker._trackEvent('Merchant Visit', merchant);
    pageTracker._trackPageview('/out/m/' + merchant);
  } catch(err) {}
}

var userInfo;

function updateLoginElements() {
  if (userInfo) {
    if (userInfo.email) $('#account_email').html('(' + userInfo.email + ')');
    $('#myShoppingListQty').html(' (' + userInfo.shopping_list_qty + ')');
    if (userInfo.logged_in) {
      $('.loggedIn').removeClass('hidden');
      $('.loggedOut').addClass('hidden');
    }
  }
}

function updatePageElements() {
  if (userInfo) {
    // Show/hide the right shopping list links
    $($.map(userInfo.shopping_list_products, function(id) { return '.remove_shopping_list[data-id=' + id + ']'; }).join(', ')).removeClass('hidden').prev().addClass('hidden');
    // Show admin controls to admins
    if (userInfo.admin) $('.adminActions, .adminHidden, .reveal').removeClass('hidden');
    // Disable the 'save this look' button
    $('#looks_show ' + $.map(userInfo.shopping_list_looks, function(id) { return '.saveLink[data-id=' + id + ']'; }).join(', ')).addClass('disabled');
  }
}

function loadUserInfo() {
  // userInfo is set with cookie on page, if not set with json as follows
  if (!userInfo) {
    $.get('/user_session/info', {}, function(data) {
      userInfo = data;
      updateLoginElements();
      updatePageElements(); 
    }, 'json');
  } else {
    updatePageElements(); 
  }
}

// Set up the main navigation menu dropdowns
$(document).ready(function(){
  loadUserInfo();
  setupPrintLinks();

  $('.hasSubMenu').hover(function() {
    $(this).addClass('expanded');
  }, function() {
    $(this).removeClass('expanded');
  });

  if($("div[data-content_id]").length){

    $(".reveal").click(function(e){
      e.preventDefault();
      window.editMode = !window.editMode;
      if(window.editMode) {
        reveal();
      }
      else {
        $(".contentMask").remove();
      }
    });
  }
  else {
    $(".reveal").hide();
  }

  // Flash messages
  $('.flash').fadeIn('slow');

  // Swap thumb images
  $('.swap.thumb').click(function(event) {
    event.preventDefault();
    $(this).parents('ul.product').find('img:eq(0)').attr('src', $(this).attr('href'));
  });

  // Ajaxify ajax forms
  // $('form.emailSubscribe').ajaxForm({
  //   success: function() { alert('You have been subscribed to the newsletter.'); }
  // });

  // Track links to merchants
  $('li.buyLink a, #shoppingListMerchants li a').click(function(e) {
    trackMerchantClick($(this).attr('data-merchant'));
  });

  $('#email').click(function(event) {
      if ( $('#email').val() == "enter email..." ) {
        $('#email').val("");
      }
  });
  $('#footer-email').click(function(event) {
      if ( $('#footer-email').val() == "enter email..." ) {
        $('#footer-email').val("");
      }
  });
  
  $('input[name=authenticity_token]').val($.cookie('authenticity_token'));
});

