/*
 * moveEditsection
 *
 * dbenzhuser (de:Benutzer:Dbenzhuser)
 * modified by: [[ja:User:Mizusumashi]]
 */
 
function moveEditsection(span)
{
    var parent = span.parentNode;
    parent.removeChild(span);
    span.className = span.className.replace('editsection',
                                            'editsection editsection-moved');
    parent.appendChild(document.createTextNode(' '));
    parent.appendChild(span);
}

function getHeadLine(span)
{
    for(var next = span.parentNode.nextSibling; next; next = next.nextSibling){
        if (typeof next.tagName != 'string'){
            continue;
        }

        var tag = next.tagName.toLowerCase();
        if( tag == 'h1'
            || tag == 'h2'
            || tag == 'h3'
            || tag == 'h4'
            || tag == 'h5'
            || tag == 'h6'){
            return next;
        }
    }

    return null;
}

function moveEditsectionExpands(span)
{
    var headline = getHeadLine(span);
    if ( ! headline){
        return;
    }

    span.parentNode.removeChild(span);
    span.className = span.className.replace('editsection-expands', 
                                            'editsection editsection-expands-moved');
    headline.appendChild(span);
}

function checkClass(span, cssClass)
{
    array = span.className.split(' ');
    
    for(var i = 0; i < array.length; i++){
        if(array[i] == cssClass){
            return true;
        }
    }
    
    return false;
}

function moveEditsectionMain()
{
    if (typeof moveEditsectionDisable != 'undefined'
        && moveEditsectionDisable){
        return;
    }

    var spans = document.getElementsByTagName('span');
    var editsection_array = new Array();
    var editsection_expands_array = new Array();
    
    for (var i = 0; i < spans.length; i++) {
        var span = spans[i];
        if(checkClass(span, 'editsection')){
            editsection_array.push(span);
        }else if(checkClass(span, 'editsection-expands')){
            editsection_expands_array.push(span);
        }
    }

    for (var i = 0; i < editsection_array.length; i++) {
        moveEditsection(editsection_array[i]);
    }

    for (var i = 0; i < editsection_expands_array.length; i++) {
        moveEditsectionExpands(editsection_expands_array[i]);
    }
}

addOnloadHook(moveEditsectionMain);