/*global isAndroid */

// This doesn't work on HTC devices with Android 4.0.
// Not much can be done about it as it seems to be a browser bug
// (it doesn't update visual styling while you hold your finger on the screen)
$.fn.tapHoldAndEnd = function(selector, callbackStart, callbackEnd) {
  return this.each(function() {
    var tapHoldStart,
        timer,
        target;

    function clearTapTimer(event) {
      clearTimeout(timer);

      if (tapHoldStart && target) {
        callbackEnd(target);
      }

      target = undefined;
      tapHoldStart = false;
    }

    $(this).on('touchstart', selector, function(event) {
        clearTapTimer();

        target = event.currentTarget;
        timer = setTimeout(function() {
          tapHoldStart = true;
          callbackStart(target);
        }, 50);
      })
      .on('touchmove touchend', clearTapTimer);

    $(document).on('touchcancel', clearTapTimer);
  });
};

//only enable on android
var useNativeHighlight = !isAndroid;
Thorax.configureTapHighlight = function(useNative, highlightClass) {
  useNativeHighlight = useNative;
  highlightClass = highlightClass || 'tap-highlight';

  if (!useNative) {
    function _tapHighlightStart(target) {
      var tagName = target && target.tagName.toLowerCase();

      // User input controls may be visually part of a larger group. For these cases
      // we want to give priority to any parent that may provide a focus operation.
      if (tagName === 'input' || tagName === 'select' || tagName === 'textarea') {
        target = $(target).closest('[data-tappable=true]')[0] || target;
      }

      if (target) {
        $(target).addClass(highlightClass);
        return false;
      }
    }
    function _tapHighlightEnd() {
      $('.' + highlightClass).removeClass(highlightClass);
    }
    $(document.body).tapHoldAndEnd(
          '[data-tappable=true], a, input, button, select, textarea',
          _tapHighlightStart,
          _tapHighlightEnd);
  }
};

var NATIVE_TAPPABLE = {
  'A': true,
  'INPUT': true,
  'BUTTON': true,
  'SELECT': true,
  'TEXTAREA': true
};

// Out here so we do not retain a scope
function NOP(){}

function fixupTapHighlight() {
  _.each(this._domEvents || [], function(bind) {
    var components = bind.split(' '),
        selector = components.slice(1).join(' ') || undefined;  // Needed to make zepto happy

    if (components[0] === 'click') {
      // !selector case is for root click handlers on the view, i.e. 'click'
      $(selector || this.el, selector && this.el).forEach(function(el) {
        var $el = $(el).data('tappable', true);

        if (useNativeHighlight && !NATIVE_TAPPABLE[el.tagName]) {
          // Add an explicit NOP bind to allow tap-highlight support
          $el.on('click', NOP);
        }
      });
    }
  }, this);
}

Thorax.View.on({
  'rendered': fixupTapHighlight,
  'rendered:collection': fixupTapHighlight,
  'rendered:item': fixupTapHighlight,
  'rendered:empty': fixupTapHighlight
});

var _addEvent = Thorax.View.prototype._addEvent;
Thorax.View.prototype._addEvent = function(params) {
  this._domEvents = this._domEvents || [];
  if (params.type === "DOM") {
    this._domEvents.push(params.originalName);
  }
  return _addEvent.call(this, params);
};
