/*
 * Copyright 2011 eBay Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * This module provides a cross-browser solution for adding event listeners
 * to DOM elements. This code is used to handle the differences between
 * IE and standards browsers. Older IE browsers use "attachEvent" while
 * newer browsers using "addEventListener".
 */
var testEl = document.body || document.createElement('div');

function IEListenerHandle(el, eventType, listener) {
    this._info = [el, eventType, listener];
}

IEListenerHandle.prototype = {
    remove: function() {
        var info = this._info;
        var el = info[0];
        var eventType = info[1];
        var listener = info[2];
        el.detachEvent(eventType, listener);
    }
};


function ListenerHandle(el, eventType, listener) {
    this._info = [el, eventType, listener];
}

ListenerHandle.prototype = {
    remove: function() {
        var info = this._info;
        var el = info[0];
        var eventType = info[1];
        var listener = info[2];
        el.removeEventListener(eventType, listener);
    }
};

/**
 * Adapt an native IE event to a new event by monkey patching it
 */
function getIEEvent() {
    var event = window.event;
    // add event.target
    event.target = event.target || event.srcElement;

    event.preventDefault = event.preventDefault || function() {
        event.returnValue = false;
    };

    event.stopPropagation = event.stopPropagation || function() {
        event.cancelBubble = true;
    };

	event.key = (event.which + 1 || event.keyCode + 1) - 1 || 0;

    return event;
}

if (!testEl.addEventListener) {
    // IE8...
    module.exports = function(el, eventType, listener) {
        function wrappedListener() {
            var event = getIEEvent();
            listener(event);
        }

        eventType = 'on' + eventType;

        el.attachEvent(eventType, wrappedListener);
        return new IEListenerHandle(el, eventType, wrappedListener);
    };
} else {
    // Non-IE8...
    module.exports = function(el, eventType, listener) {
        el.addEventListener(eventType, listener, false);
        return new ListenerHandle(el, eventType, listener);
    };
}
