'use strict';

var cls = require('./class');
var dom = require('./dom');

var toInt = exports.toInt = function (x) {
  return parseInt(x, 10) || 0;
};

var clone = exports.clone = function (obj) {
  if (!obj) {
    return null;
  } else if (Array.isArray(obj)) {
    return obj.map(clone);
  } else if (typeof obj === 'object') {
    var result = {};
    for (var key in obj) {
      result[key] = clone(obj[key]);
    }
    return result;
  } else {
    return obj;
  }
};

exports.extend = function (original, source) {
  var result = clone(original);
  for (var key in source) {
    result[key] = clone(source[key]);
  }
  return result;
};

exports.isEditable = function (el) {
  return dom.matches(el, "input,[contenteditable]") ||
         dom.matches(el, "select,[contenteditable]") ||
         dom.matches(el, "textarea,[contenteditable]") ||
         dom.matches(el, "button,[contenteditable]");
};

exports.removePsClasses = function (element) {
  var clsList = cls.list(element);
  for (var i = 0; i < clsList.length; i++) {
    var className = clsList[i];
    if (className.indexOf('ps-') === 0) {
      cls.remove(element, className);
    }
  }
};

exports.outerWidth = function (element) {
  return toInt(dom.css(element, 'width')) +
         toInt(dom.css(element, 'paddingLeft')) +
         toInt(dom.css(element, 'paddingRight')) +
         toInt(dom.css(element, 'borderLeftWidth')) +
         toInt(dom.css(element, 'borderRightWidth'));
};

function toggleScrolling(handler) {
  return function (element, axis) {
    handler(element, 'ps--in-scrolling');
    if (typeof axis !== 'undefined') {
      handler(element, 'ps--' + axis);
    } else {
      handler(element, 'ps--x');
      handler(element, 'ps--y');
    }
  };
}

exports.startScrolling = toggleScrolling(cls.add);

exports.stopScrolling = toggleScrolling(cls.remove);

exports.env = {
  isWebKit: 'WebkitAppearance' in document.documentElement.style,
  supportsTouch: (('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch),
  supportsIePointer: window.navigator.msMaxTouchPoints !== null
};

@@ -1872,16 +1872,51 @@
 sWebKit:
+ typeof document !== 'undefined' &&
  'Webkit
@@ -1978,16 +1978,49 @@
 tsTouch:
+ typeof window !== 'undefined' &&
  (('onto
@@ -2130,16 +2130,49 @@
 Pointer:
+ typeof window !== 'undefined' &&
  window.

Add env check to allow running on node.js