/*
 * jQuery autoLabes plugin
 * version: 1.0
 * 
 * requires: jQuery library (version 1.2.6 or higher)
 * settings:
 *      auto - Auto searching for text or tags for labels (defaut: true)
 *
 * using:
 *      $().autoLabels();               // searching in all document
 *      $('#somediv').autoLabels();
 *      $().autoLabels({auto: false});
 *      $().autoLabels({auto: false, from: ['title','value']});
 *      $().autoLabels({auto: true, from: ['alt'], nbsp: 2});
 *
 * author: Alex Kobozev
 * e-mail: kobozevalexander@gmail.com
 */
$.fn.autoLabels = function(settings){

    // обрезает пробелы на обоих концах переданной строки
    trim = function(str){
        return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };
    // параметры
    settings = jQuery.extend({
        auto : true,     // автопоиск текста для тега Label
        from : ['alt','title','rel'],
        nbsp : 1
    }, settings);
    
    settings.nbspstring = '';
    if (settings.nbsp != 0){
        for(i=0;i<settings.nbsp;i++){
            settings.nbspstring += '&nbsp;';
        }
    }
    
    // если не установлен, то устанавливаем счётчик
    if (!$.autoLabels_counter){
        $.autoLabels_counter = 0;
    }
    if (this){
        this.find('input[type=checkbox], input[type=radio]').each(function(){
            // увеличиваем счётчик
            $.autoLabels_counter++;
            
            nodeval = '';            
            // автопоиск следующего DOM элемента за найденым
            if (settings.auto){
	            next = $(this).get(0).nextSibling;
	            // если найденный элемент типа текст то пытаемся превратить его в лейбл
	            if (next && next.nodeType == 3){
	                nodeval = next.nodeValue;
	                nextnext = next.nextSibling;
	                // убираем пробелы (trim)
	                nodeval = trim(nodeval);
	                if (nodeval == '' || (nextnext && nextnext.nodeType == 1 &&
	                    (nextnext.tagName == "B" || nextnext.tagName == "U" ||nextnext.tagName == "I" ||
	                     nextnext.tagName == "SPAN" || nextnext.tagName == "FONT" || nextnext.tagName == "DIV"))){
	                            if (nextnext.firstChild && nextnext.firstChild.nodeType == 3){
	                                nodeval = nextnext.firstChild.nodeValue;
	                                // возвращяем тег в котором был текст
	                                nodeval = '<' + nextnext.tagName + '>' + trim(nodeval) + '</' + nextnext.tagName + '>';
	                                $(nextnext).remove();
	                            }
	                }
	                $(next).remove();
	            }
	            // если найденный элемент это тег, то посмотрим что у него внутри 
	            else if (next && next.nodeType == 1 && (next.tagName == "B" || next.tagName == "U" || next.tagName == "I" ||
	                next.tagName == "SPAN" || next.tagName == "FONT" || next.tagName == "DIV")){
	                // если внутри тега текст то вытаскиваем его
	                if (next.firstChild && next.firstChild.nodeType == 3){
	                    nodeval = next.firstChild.nodeValue;
	                    // возвращяем тег в котором был текст
	                    nodeval = '<' + next.tagName + '>' + trim(nodeval) + '</' + next.tagName + '>';
	                    $(next).remove();
	                }
	            }
            }

            // ищем текст который будет лейбл текстом
            //label_text = (nodeval != '' ? nodeval : (this.alt ? this.alt : (this.title ? this.title : (this.rel ? this.rel : '') )));
            nodeattrval = '';
            for(at in settings.from){
                a = settings.from[at];
                if ($(this).attr(a)){
                    nodeattrval = $(this).attr(a);
                    break;
                }
            }
            label_text = (nodeval != '' ? nodeval : (nodeattrval != '' ? nodeattrval : ''));
            
            if (label_text != ''){
                newID = 'label' + $.autoLabels_counter;
                if ($(this).attr('id')){
                    newID = $(this).attr('id');
                }
	            $('<label for="'+newID+'">' + settings.nbspstring + label_text+'</label>').insertAfter(this);
	            // ставим инпуту id
	            $(this).attr('id',newID);
            }
        });
    }
}
