switchNames = function(newElem, oldElem)
{
    // Aendert die Werte der Eingabe Felder der beiden Tabellenspalten
    if (newElem.length > 0 && oldElem.length > 0) {
        newElem.attr('id', oldElem.attr('id'))
        newElements = $('input, select', newElem)
        oldElements = $('input, select', oldElem).toArray()

        newElements.each(function(index, element){
            tempElem = $(oldElements[index])
            $(element)
                .attr('id', tempElem.attr('id'))
                .attr('name', tempElem.attr('name'))
        })
    }
}

addRow = function(){
    numberForms = $('#id_search_fields-TOTAL_FORMS')
    n = parseInt(numberForms.attr('value')) + 1
    numberForms.attr('value', n.toString())
    url = $(this).attr('href')
    if(url){
        row = $(this).parents("tr")
        $.get(url, {rownumber: n - 1}, function(data){
            newrow = $(data)
            row
                .after(newrow)
            $('.searchPlusMinus .searchPlus', newrow)
                .bind('click', addRow)
            $('.searchPlusMinus .searchMinus', newrow)
                .bind('click', removeRow)
            clone = newrow.clone()
            newrow.nextAll().reverse().each(function(index, element){
                elem = $(element)
                switchNames(elem.prev(), elem)
            })
            switchNames(newrow.nextAll().last(), clone)
        })
    }
}

removeRow = function()
{
    if($('.searchFields tbody tr').length > 1)
    {
        row = $(this).parents("tr")
        switchNames(row.next(), row)
        row.nextAll()
            .each(function(index, element){
                elem = $(element)
                switchNames(elem, elem.prev())
            })
        row.remove()
        numberForms = $('#id_search_fields-TOTAL_FORMS')
        n = parseInt(numberForms.attr('value')) - 1
        numberForms.attr('value', n.toString())
    }
}

$(document).ready(function(){

    $('#img_searchform_longview').bind("click", function(){
        $('#id_search_extra-searchtype')
            .attr('checked', 'checked')
            .trigger('change');
        $(this)
            .parent()
                .addClass('searchViewControlsLong')
    })
    $('#img_searchform_shortview').bind("click", function(){
        $('#id_search_extra-searchtype')
            .attr('checked', '')
            .trigger('change');
        $(this)
            .parent()
                .removeClass('searchViewControlsLong')
    })

    $('.searchPlus')
        .bind('click', addRow)
    $('.searchMinus')
        .bind('click', removeRow)
})
