/*
 * form.js
 * -------
 *
 *  questo JS contiene il codice per customizzare le form di lucyinthesky.it;
 *  questo file contiene solo codice di libreria *indipendente* dal
 *  contenuto della specifica pagina.
 */
GEO_URL = '/members/geo?';
INCLUDE_EMPTY_OPTION = true;
SHOW_GEO_WARNING = false;
GEO_DEFAULT_OPTION = '!italia';

_Editors = {};

function smart_form() {
    function requestGeoLevel(key, cb) {
        /*
         * richiede al server il livello del thesauro geografico figlio di
         * key. cb viene invocata quando i dati sono disponibili.
         */
        jQuery.getJSON(GEO_URL + jQuery.param({ 'parent': key }), cb);
    };
    var geo_field = function() {
        /*
         * this e' un input box accanto al quale creo una combobox.
         * La combobox mostra il primo livello del thesauro geografico;
         * non appena viene scelto un elemento tra quelli disponibili creo
         * una nuova combobox che mostra i termini del livello seguente figli
         * dell'elemnto scelto.
         * in this viene impostato l'id del termine scelto.
         */
        var geoField = this;
        $(this).nextAll('select._geo_select').remove();
        function _create_geocbox(brother, pkey, dkey, callback) {
            /*
             * crea una nuova combobox accanto a brother.
             * target e' l'input field che conterra' l'id del termine scelto.
             */
            var cbox = $('<select class="_geo_select"></select>').appendTo($(brother).parent());
            var cb = function(entries) {
                if(!entries.length) {
                    cbox.remove();
                    return;
                }
                var select = cbox.get(0);
                if(INCLUDE_EMPTY_OPTION) {
                    select.options[0] = new Option('', '');
                    var sx = 1;
                }
                else {
                    var sx = 0;
                }
                for(var ix=0; ix<entries.length; ix++) {
                    select.options[ix+sx] = new Option(entries[ix][1], entries[ix][0]);
                }
                if(dkey) {
                    for(var ix=0; ix<entries.length; ix++) {
                        if(entries[ix][0] == dkey || (dkey.substr(0, 1) == '!' && entries[ix][1].toLowerCase() == dkey.substr(1))) {
                            select.selectedIndex = ix+sx;
                            break;
                        }
                    }
                }
                cbox.show();
                if(callback)
                    callback(select);
            };
            cbox.hide();
            requestGeoLevel(pkey, cb);
            return cbox;
        }
        var onChange = function() {
            /*
             * ogni volta che viene selezionato un elemento:
             * 1. distruggo tutte le select dopo this.
             * 2. valorizzo target.
             * 3. creo una nuova select
             */
            $(this).nextAll('select').remove();
            geoField.value = this.options[this.selectedIndex].value;
            if(geoField.value) {
                var cbox = _create_geocbox(this, geoField.value, null);
                cbox.bind('change', onChange);
            }

            if(SHOW_GEO_WARNING) {
                var p = $(this).parent('div');
                var nation = p.children('select').get(0);
                nation = nation.options[nation.selectedIndex];
                nation = nation.childNodes[0].nodeValue.toLowerCase()
                var label = $('label span.dentry', p);
                if(label.length == 0) {
                    label = jQuery('<span class="dentry" />').appendTo(p.children('label'));
                }
                if(nation == 'italia') {
                    label.text('ricorda di selezionare almeno un comune');
                }
                else {
                    label.text('la tua città non è presente? Inseriscila nel messaggio per l\'Associazione');
                }
            }
        };
        var cbox = null;
        var key = this.value;
        var last_cb = function(c) { onChange.call(c) }
        if(key.length == 0) {
            cbox = _create_geocbox(
                this, '', GEO_DEFAULT_OPTION, last_cb
            );
            cbox.bind('change', onChange);
        }
        else {
            var ex = 0;
            var brother = this;
            while(ex < key.length) {
              var parent_key = key.substr(0, ex);
              var default_key = key.substr(0, ex + 3);
              if(ex != key.length - 3) {
                cbox = _create_geocbox(
                  brother, parent_key, default_key
                );
              }
              else {
                cbox = _create_geocbox(
                  brother, parent_key, default_key, last_cb
                );
              }
              cbox.bind('change', onChange);
              ex += 3;
              brother = cbox.get(0);
            }
        }
    };
    var color_field = function() {
        var colpkr = $('<input type="text" />').appendTo($(this).parent());
        var s = this;
        $(colpkr).ColorPicker({
            onShow: function(colpkr) {
                $(colpkr).fadeIn(500);
                return false;
            },
            onHide: function(colpkr) {
                $(colpkr).fadeOut(500);
                return false;
            },
            onChange: function(hsb, hex, rgb) {
                $(colpkr).css('backgroundColor', '#' + hex);
                $(s).val("#" + hex);
            }

        });
    }
    var date_field = function() {
        $(this).datepicker({
            mandatory: true,
            highlightWeek: true,
            duration: '',
            dateFormat: 'dd/mm/yy'
        });
    }
    var textarea_field = function() {
        var id = this.id;
        var T = $(this);
        if(T.hasClass('wym_html_val'))
            return;
        if(id in _Editors) {
            setTimeout(function() { _Editors[id].html(T.val()) }, 300);
        }
        else {
            T.wymeditor({
                updateSelector: "input:submit",
                updateEvent: "click",
                postInit: function(wym) {
                    _Editors[id] = wym;
                },
                lang: 'it',
                toolsItems: [
                    {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}, 
                    {'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
                    {'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'},
                    {'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
                    {'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
                    {'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'}
                ],
                'containersHtml': '',
                'classesHtml': ''
            });
        }
    };
    /*
     * Nei div con classe ".form-geo-field" viene aggiunta la
     * gestione dell'albero geografico collegato all'input field
     * nascosto
     *
     */
    $('.form-geo-field input', this).each(geo_field);
    $('.form-color-field input', this).each(color_field);
    $('.form-date-field input', this).each(date_field);
    $('div textarea', this).each(textarea_field);
};

function updateAllEditorsSource() {
    for(var key in _Editors) {
        _Editors[key].update();
    }
};

$(document).ready(function() {
    /*
     * solo le form con classe ".smart-form" vengono analizzate e modificate.
     */
    var forms = $('form.smart-form');
    forms.each(smart_form);
    if(forms.length)
        $('input', forms).get(0).focus();
    var tabs = $('ul.tabs')
    tabs.each(function() { autoTabs($(this).parent()); });
});

