var DU;
if (!DU) DU = {};

DU.Hyph = {
    tags: '#headHyph, #hyph > p, #hyph > ul',
    tshy: '&shy;',
    shy: null,
    spec: '[éüú]',
    vovel: '[àå¸èîóûýþÿaeiouy]',
    consonant: '(?:sh|ch|qu|[áâãäæçêëìíïðñòôõö÷øùbcdfghjklmnpqrstvwxz])',
    letters: '[üúéàå¸èîóûýþÿáâãäæçéêëìíïðñòôõö÷øùúüaeiouybcdfghjklmnpqrstvwxz]',
    rules: null,
    elements: [],
    
    getApplyMethod: function() {
        return 'text-align:justify;';
    },
    
    hyphenizeText: function(text) {
        for (var i = this.rules.length - 1; i >= 0; i--) {
            var ru = this.rules[i];
            
            if (!ru) {
                continue;
            }
            
            var re = new RegExp('(' + ru[0] + ')(?=' + ru[1] + ')', 'gi');
            
            text = text.replace(re, '$1' + this.shy);
        }
        
        return text;
    },
    
    hyphenize: function(node) {
        var n = node;
        var children = n.childNodes;
        var parent = node.parentNode;
        
        if (node.nodeType == 3) {
            if (!node.nodeValue) {
                return;
            }
            
            node.nodeValue = this.hyphenizeText(node.nodeValue);
            DU.Functions.attr(parent, 'style', this.getApplyMethod());
        }
        
        for (var i = 0; i < children.length; i++) {
            this.hyphenize(children[i]);
        }
    },
    
    afterLoadExec: function() {
        this.elements = DU.cssQuery(this.tags);
        //alert(this.elements);
        if (this.elements.length <= 0) {
            return;
        }
        
        for (var e = 0; e < this.elements.length; e++) {
            this.hyphenize(this.elements[e]);
        }
    },
    
    _init: function() {
        if (! this.shy) {
            var node = document.createElement('span');
            node.innerHTML = this.tshy;
            
            this.shy = node.childNodes[0].nodeValue;
            
            with (this) {
                rules = [
                    [consonant + vovel, vovel + letters],
                    [vovel + consonant, consonant + vovel],
                    [consonant + vovel, consonant + vovel],
                    [vovel + consonant, consonant + consonant + vovel],
                    [vovel + consonant + consonant, consonant + vovel],
                    [vovel + consonant + consonant, consonant + consonant + vovel],
                    [spec, letters + letters],
                    null
                ];
            }
        }
    }
};

DU.Hyph._init();
// DU.Functions.addEvent(window, 'load', function() {DU.Hyph.afterLoadExec();});