﻿jQuery(document).ready( (new doWrap()).go );
function doWrap() {   
    defaultBreakChar = 8203;
    defaultWordlen = 45;
    var textnodes;
    
    function wordBreaker(word, wordlen, breakchar) {
        breakchar = breakchar == undefined ?  defaultBreakChar : breakchar;
        re = new RegExp("[_\\-&/+\\/=\\\\]", 'g');
        word = word.replace(re, String.fromCharCode(breakchar) + '$&' + String.fromCharCode(breakchar));
        chars = word.split(String.fromCharCode(breakchar));
        for(var i=0;i<chars.length;i++){
            if(chars[i].length > wordlen) {
                var newchar = '';
                for(var j = 0; j < Math.ceil(chars[i].length/wordlen); j++){
                    newchar = newchar + chars[i].substr(j*wordlen, wordlen) + String.fromCharCode(breakchar);
                }
                chars[i] = newchar;
            }
        }
        return chars.join(String.fromCharCode(breakchar)) + String.fromCharCode(breakchar);
    }
    
    function getTextNodes(nodes) {
        for(var k = 0; k< nodes.length; k++) {
            if(nodes[k].hasChildNodes()){
                getTextNodes(nodes[k].childNodes);
            } else if(nodes[k].nodeType == 3) {    //TEXT_NODE
                textnodes[textnodes.length] = nodes[k];
            }
        }
    }
    
    this.go =function () {
        if(jQuery.browser.msie && jQuery.browser.version < 7) {
            return;
        } else {
            jQuery('.wordwrap').each(function(idx){
                wordlen = jQuery(this).attr('class').split('-')[1] == null ? defaultWordlen : jQuery(this).attr('class').split('-')[1];
                textnodes = new Array();
                getTextNodes(this.childNodes);
                for(var i=0;i< textnodes.length; i++){
                    texts = textnodes[i].nodeValue.split(' ');
                    for(var j=0;j<texts.length;j++){
                        if(texts[j].length > wordlen) {
                            texts[j] = wordBreaker(texts[j], wordlen, 8203) ;
                        }
                    }
                    texts = texts.join(' ') + String.fromCharCode('8203');   
                    textnodes[i].nodeValue = texts;
                    
                }
            });
        }
    }
    
}