/**
 * Move a category before the a  given element of its hierarchy level
 *
 * @param object $the_term
 * @param int $next_id the id of the next slibling element in save hierachy level
 * @param int $index
 * @param int $terms
 * @return int
 */
function fflcommerce_order_categories($the_term, $next_id, $index = 0, $terms = null)
{
    if (!$terms) {
        $terms = get_terms('product_cat', 'menu_order=ASC&hide_empty=0&parent=0');
    }
    if (empty($terms)) {
        return $index;
    }
    $id = $the_term->term_id;
    $term_in_level = false;
    // flag: is our term to order in this level of terms
    foreach ($terms as $term) {
        if ($term->term_id == $id) {
            // our term to order, we skip
            $term_in_level = true;
            continue;
            // our term to order, we skip
        }
        // the nextid of our term to order, lets move our term here
        if (null !== $next_id && $term->term_id == $next_id) {
            $index++;
            $index = fflcommerce_set_category_order($id, $index, true);
        }
        // set order
        $index++;
        $index = fflcommerece_set_category_order($term->term_id, $index);
        // if that term has children we walk through them
        $children = get_terms('product_cat', "parent={$term->term_id}&menu_order=ASC&hide_empty=0");
        if (!empty($children)) {
            $index = fflcommerce_order_categories($the_term, $next_id, $index, $children);
        }
    }
    // no nextid meaning our term is in last position
    if ($term_in_level && null === $next_id) {
        $index = fflcommerce_set_category_order($id, $index + 1, true);
    }
    return $index;
}
/**
 * Ajax request handling for categories ordering
 */
function fflcommerce_categories_ordering()
{
    $id = (int) $_POST['id'];
    $next_id = isset($_POST['nextid']) && (int) $_POST['nextid'] ? (int) $_POST['nextid'] : null;
    if (!$id || !($term = get_term_by('id', $id, 'product_cat'))) {
        die(0);
    }
    fflcommerce_order_categories($term, $next_id);
    $children = get_terms('product_cat', "child_of={$id}&menu_order=ASC&hide_empty=0");
    if ($term && sizeof($children)) {
        echo 'children';
        die;
    }
}