/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function (require, exports, module) {
    "use strict";

    var dom = require("../lib/dom");
    var isIE8;

    var Cursor = function (parentEl) {
        this.element = dom.createElement("div");
        this.element.className = "ace_layer ace_cursor-layer";
        parentEl.appendChild(this.element);

        if (isIE8 === undefined)
            isIE8 = !("opacity" in this.element.style);

        this.isVisible = false;
        this.isBlinking = true;
        this.blinkInterval = 1000;
        this.smoothBlinking = false;

        this.cursors = [];
        this.cursor = this.addCursor();
        dom.addCssClass(this.element, "ace_hidden-cursors");
        this.$updateCursors = (isIE8
            ? this.$updateVisibility
            : this.$updateOpacity).bind(this);
    };

    (function () {

        this.$updateVisibility = function (val) {
            var cursors = this.cursors;
            for (var i = cursors.length; i--;)
                cursors[i].style.visibility = val ? "" : "hidden";
        };
        this.$updateOpacity = function (val) {
            var cursors = this.cursors;
            for (var i = cursors.length; i--;)
                cursors[i].style.opacity = val ? "" : "0";
        };


        this.$padding = 0;
        this.setPadding = function (padding) {
            this.$padding = padding;
        };

        this.setSession = function (session) {
            this.session = session;
        };

        this.setBlinking = function (blinking) {
            if (blinking != this.isBlinking) {
                this.isBlinking = blinking;
                this.restartTimer();
            }
        };

        this.setBlinkInterval = function (blinkInterval) {
            if (blinkInterval != this.blinkInterval) {
                this.blinkInterval = blinkInterval;
                this.restartTimer();
            }
        };

        this.setSmoothBlinking = function (smoothBlinking) {
            if (smoothBlinking != this.smoothBlinking && !isIE8) {
                this.smoothBlinking = smoothBlinking;
                dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking);
                this.$updateCursors(true);
                this.$updateCursors = (this.$updateOpacity).bind(this);
                this.restartTimer();
            }
        };

        this.addCursor = function () {
            var el = dom.createElement("div");
            el.className = "ace_cursor";
            this.element.appendChild(el);
            this.cursors.push(el);
            return el;
        };

        this.removeCursor = function () {
            if (this.cursors.length > 1) {
                var el = this.cursors.pop();
                el.parentNode.removeChild(el);
                return el;
            }
        };

        this.hideCursor = function () {
            this.isVisible = false;
            dom.addCssClass(this.element, "ace_hidden-cursors");
            this.restartTimer();
        };

        this.showCursor = function () {
            this.isVisible = true;
            dom.removeCssClass(this.element, "ace_hidden-cursors");
            this.restartTimer();
        };

        this.restartTimer = function () {
            var update = this.$updateCursors;
            clearInterval(this.intervalId);
            clearTimeout(this.timeoutId);
            if (this.smoothBlinking) {
                dom.removeCssClass(this.element, "ace_smooth-blinking");
            }

            update(true);

            if (!this.isBlinking || !this.blinkInterval || !this.isVisible)
                return;

            if (this.smoothBlinking) {
                setTimeout(function () {
                    dom.addCssClass(this.element, "ace_smooth-blinking");
                }.bind(this));
            }

            var blink = function () {
                this.timeoutId = setTimeout(function () {
                    update(false);
                }, 0.6 * this.blinkInterval);
            }.bind(this);

            this.intervalId = setInterval(function () {
                update(true);
                blink();
            }, this.blinkInterval);

            blink();
        };

        this.getPixelPosition = function (position, onScreen) {
            if (!this.config || !this.session)
                return {left: 0, top: 0};

            if (!position)
                position = this.session.selection.getCursor();
            var pos = this.session.documentToScreenPosition(position);
            var cursorLeft = this.$padding + pos.column * this.config.characterWidth;
            var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) *
                this.config.lineHeight;

            return {left: cursorLeft, top: cursorTop};
        };

        this.update = function (config) {
            this.config = config;

            var selections = this.session.$selectionMarkers;
            var i = 0, cursorIndex = 0;

            if (selections === undefined || selections.length === 0) {
                selections = [{cursor: null}];
            }

            for (var i = 0, n = selections.length; i < n; i++) {
                var pixelPos = this.getPixelPosition(selections[i].cursor, true);
                if ((pixelPos.top > config.height + config.offset ||
                    pixelPos.top < 0) && i > 1) {
                    continue;
                }

                var style = (this.cursors[cursorIndex++] || this.addCursor()).style;

                if (!this.drawCursor) {
                    style.left = pixelPos.left + "px";
                    style.top = pixelPos.top + "px";
                    style.width = config.characterWidth + "px";
                    style.height = config.lineHeight + "px";
                } else {
                    this.drawCursor(style, pixelPos, config, selections[i], this.session);
                }
            }
            while (this.cursors.length > cursorIndex)
                this.removeCursor();

            var overwrite = this.session.getOverwrite();
            this.$setOverwrite(overwrite);

            // cache for textarea and gutter highlight
            this.$pixelPos = pixelPos;
            this.restartTimer();
        };

        this.drawCursor = null;

        this.$setOverwrite = function (overwrite) {
            if (overwrite != this.overwrite) {
                this.overwrite = overwrite;
                if (overwrite)
                    dom.addCssClass(this.element, "ace_overwrite-cursors");
                else
                    dom.removeCssClass(this.element, "ace_overwrite-cursors");
            }
        };

        this.destroy = function () {
            clearInterval(this.intervalId);
            clearTimeout(this.timeoutId);
        };

    }).call(Cursor.prototype);

    exports.Cursor = Cursor;

});
