/**
 * MUI CSS/JS animation helper module
 * @module lib/animationHelpers
 */

'use strict';

var jqLite = require('./jqLite'),
    util = require('./util'),
    animationEvents = 'animationstart mozAnimationStart webkitAnimationStart',
    animationCallbacks = {};


/**
 * Register callbacks
 * @param {String} name - The animation name
 * @param {Function} callbackFn = The callback function
 */
function onAnimationStartFn(name, callbackFn) {
  // get/set callback function
  var callbacks = animationCallbacks[name];
  if (!callbacks) callbacks = animationCallbacks[name] = [];
  callbacks.push(callbackFn);

  // initialize listeners
  if (!this.init) {
    // add css classes
    loadCss();

    // add listener
    jqLite.on(document, animationEvents, animationStartHandler, true);

    // set flag
    this.init = true;
  }
}


/**
 * Animation start handler
 * @param {Event} ev - The DOM event
 */
function animationStartHandler(ev) {
  var callbacks = animationCallbacks[ev.animationName] || [],
      i = callbacks.length;

  // exit if a callback hasn't been registered
  if (!i) return;
  
  // stop other callbacks from firing
  ev.stopImmediatePropagation();

  // iterate through callbacks
  while (i--) callbacks[i](ev);
}


/**
 * Load animation css
 */
function loadCss() {
  // define rules
  var rules = [
    ['.mui-btn', 'mui-btn-inserted'],
    ['[data-mui-toggle="dropdown"]', 'mui-dropdown-inserted'],
    [
      '.mui-btn[data-mui-toggle="dropdown"]',
      'mui-btn-inserted,mui-dropdown-inserted'
    ],
    ['[data-mui-toggle="tab"]', 'mui-tab-inserted'],
    ['.mui-textfield > input', 'mui-textfield-inserted'],
    ['.mui-textfield > textarea', 'mui-textfield-inserted'],
    ['.mui-select > select', 'mui-select-inserted'],
    ['.mui-select > select ~ .mui-event-trigger', 'mui-node-inserted'],
    ['.mui-select > select:disabled ~ .mui-event-trigger', 'mui-node-disabled']
  ];

  // build css
  var css = '',
      rule;

  for (var i=0, m=rules.length; i < m; i++) {
    rule = rules[i];
    // use an IE-only property to trigger animation cross-browser
    css += '@keyframes ' + rule[1] + '{from{-ms-zoom:1;}to{-ms-zoom:1;}}';
    css += rule[0];
    css += '{animation-duration:0.0001s;animation-name:' + rule[1] + ';}';
  }
  
  // add CSS to DOM
  util.loadStyle(css);
}


/**
 * Define module API
 */
module.exports = {
  animationEvents: animationEvents,
  onAnimationStart: onAnimationStartFn
}
