/**
 * Create a simple dialog with some content and maybe even buttons
 * 
 * The `ep.uiSimpledialog()` creates a simple dialog with a close button. This dialog also closes automatically, when a click occurs outside the dialog.
 * 
 * ### Examples
 * Create a simple dialog with some content and a button with a callback function.
 * 
 * JavaScript:
 * 
 *     ep('#ep-edit').uiSimpledialog({
 *     content : $('<div>Some content.</div>'),
 *     buttons : [{
 *     text : 'test',
 *     callback : function () {
 *     alert('The "test" button was clicked!');
 *     }
 *     }]
 *     });
 * 
 * HTML:
 * 
 *     <button id="ep-edit">Edit</button>
 * 
 * 
 * @class jQuery.ui.uiSimpledialog
 * @extends jQuery.widget
 * 
 * @uses jQuery.tmpl
 * @uses jQuery.ui.widget
 * @uses jQuery.ui.draggable
 * @uses ep
 * @uses ep.fn.contextOrientation
 * @uses ep.ui.input
 * @since 6.15.0
 */

/**
 * Close the dialog.,Open the dialog.,Removes the dialog functionality completely. This will return the element back to its pre-init state
 * 
 * @method close,open,destroy
 * @member jQuery.ui.uiSimpledialog
 * 
 * @since 6.15.0,6.15.0,6.15.0,6.15.0,6.15.0,6.15.0,6.15.0,6.15.0,6.15.0,6.15.0
 */

/**
 * See `jQuery.ui.uiSimpledialog` for details.
 * 
 * @param {Object} options A map of additional options pass to the method.
 * 
 * @method uiSimpledialog
 * @member jQuery
 * 
 * @since 6.15.0
 */

/*
 * @copyright       © Copyright 2006-2011, epages GmbH, All Rights Reserved.
 *
 * @module          ep.ui.simpledialog
 */

/*jslint nomen: true*/
/*global define, setTimeout*/
define("ep/ui/simpledialog", [
    "jquery",
    "ep",
    "$tmpl!ep/ui/simpledialog",

    "jquery/ui/widget",
    "jquery/ui/draggable",
    "ep/ui/input",
    "ep/fn/contextorientation"
], function ($, ep, tmplSimpledialog) {
    'use strict';
    var html = $('html');

    $.widget('ui.uiSimpledialog', {

        options : {
            autoOpen : false,
            orientation : 'bottom',
            orientationAdjust : [0, 0]
            // zIndex
            // content
            // buttons
        },

        _create : function () {
            var self = this,
                o = self.options;

            // Add *click* listener to *open* dialog.
            self.element
                .on('click.uiSimpledialog', $.proxy(self, 'open'));
        },

        _init : function () {
            var self = this,
                o = self.options;

            // If *autoOpen* is true, *open* dialog.
            if (o.autoOpen) {
                self.open();
            }
        },

        _build : function () {
            // Build dialog, if it has not been built yet.
            if (!this.dialog) {
                var self = this,
                    o = self.options,
                    colorpicker;

                // Load template and push named tmpl elements to current instance.
                $.extend(self, tmplSimpledialog([o]).tmplItem('elements'));

                // Setup *dialog*.
                self.dialog
                    .hide()
                    .appendTo('body')
                    .draggable({
                        containment : 'window',
                        handle : '.ep-uiSimpledialog-head'
                    });

                // Init content, buttons and zIndex.
                self._setOptions(o);

                // Add *click* listener to *closeButton*. (The 'x' on the upper right.)
                self.closeButton.on('click', $.proxy(self, 'close'));
            }
        },

        _setOption : function (key, value) {
            var self = this,
                o = self.options;

            switch (key) {
            case 'zIndex':
                self.dialog.css('z-index', value);
                break;

            case 'content':
                // Remove any old *content*.
                self.content.empty();
                // Add *content*.
                self.content.append(value);
                break;

            case 'buttons':
                // Init empty button div.
                if (self.buttons) {
                    self.buttons.remove();
                    self.buttons = null;
                }
                if ($.isArray(value)) {
                    // Fill div with buttons.
                    self.buttons = $('<div class="ep-uiSimpledialog-buttons"></div>').appendTo(self.dialog);
                    $.each(value, function (i, value) {
                        ep('<button type="button"></button>')
                            .text(value.text)
                            .on('click', value.callback)
                            .uiInput()
                            .appendTo(self.buttons);
                    });
                }
                break;

            }

            self._superApply(arguments);
        },


        open : function (elem) {
            var self = this,
                o = self.options,
                elem = elem ? elem : self.element;

            self._build();
            self.dialog
                .show()
                .contextOrientation(elem, o.orientation, o.orientationAdjust);

            // Move in other thread, required if simpledialog is created by click an element
            setTimeout(function () {
                html.on('click.uiSimpledialog', $.proxy(self, '_close'));
            }, 1);

            // Fire *open* event.
            self.element.trigger('open');
        },

        close : function () {
            var self = this;

            if (self.dialog) {
            // If there is no dialog, there is nothing to be closed.
                self.dialog.hide();
                html.off('click.uiSimpledialog', $.proxy(self, '_close'));

                // Fire *close* event.
                self.element.trigger('close');
            }
        },

        _close : function (event) {
            var self = this,
                elem    = self.element,
                target = $(event.originalTarget || event.target);

            if ((!$.contains(elem[0], target[0]) && target[0] !== elem[0] && !target.is('.ep-uiSimpledialog, .ep-uiSimpledialog *')) && !target.hasClass("ColorBox")) {
            // We would not want to *close* the dialog, if the *click event* was fired from inside the dialog or if the event target is a dojo colorbox event.
                self.close();
            }
        },

        destroy : function () {
            this.close();
            this.element.off('click.uiSimpledialog');
            if (this.dialog) {
                this.dialog.remove();
            }
            this._superApply(arguments);
        }

    });

    return ep;

});