<?php
// $Id: actionview_taxonomy.inc

/**
 * This include file implements actionviews functionality on behalf of taxonomy.module
 */

// permissions
$actionview_permissions[] = 'multiple edit of node taxonomy';

/**
 * Invoke hook_views_operations() for allow edit taxonomy
 *
 * @return array
 */
function taxonomy_views_operations($nodes = NULL)
{
	global $form_values;
	$operations = array();

	if (user_access('multiple edit of node taxonomy')) {
		// get fields only for this node type
		$n = reset($nodes);
		$node  = node_load(array('nid' => $n->nid));
		if (!actionview_check_node_type($nodes, $node->type))
		{
			return $operations;
		}

		// form fields for each taxonomy field
		$form = array();
		$form['type']['#value'] = $node->type;
		$form['#node'] = $node;
		taxonomy_form_alter($node->type.'_node_form', $form);

		if (count($form['taxonomy']))
		{

			foreach ($form['taxonomy'] as $key => $value)
			{
				
				if (is_array($value) && $key != 'tags')
				{
					$key = 'taxonomy_'.$key;
					$elem = array();
					$elem['form'][$key] = $value;
					$edit_field_operations['edit_node_field-'.$key] = array('label' => t('Edit Category: ').$value['#title']);
					$edit_field_operations['form_fields_'.$key] = $elem;
				}

			}
			
			if (count($form['taxonomy']['tags']))
			{

				foreach ($form['taxonomy']['tags'] as $key => $value)
				{
					if ($value['#type'] != 'fieldset')
					{
						$key = 'taxonomy_tags_'.$key;
						$elem = array();
						$elem['form'][$key] = $value;
						$edit_field_operations['edit_node_field-'.$key] = array('label' => t('Edit Tags: ').$value['#title']);
						$edit_field_operations['form_fields_'.$key] = $elem;
					}

				}
			}
			$operations = $edit_field_operations;
		}
	}
	return  $operations;
}

/**
 * Creates valid taxonomy field from form values
 *
 * @param string $form_id
 * @param array $form_values
 */
function  taxonomy_views_operations_validate($form_id, &$form_values)
{
	foreach ($form_values['nodes'] as $key => $node)
	{
		$node_fileds = get_object_vars($node);
		$old_taxonomy = $node->taxonomy;
		$form_values['nodes'][$key]->taxonomy = array();
		foreach ($old_taxonomy as $tid => $term)
		{
			$form_values['nodes'][$key]->taxonomy[$term->vid][$term->tid] = $term->tid;
		}
		foreach ($node_fileds as $field => $value)
		{
			$a = explode('_', $field);
			if (sizeof($a) > 1 && $a[0] == 'taxonomy')
			{
				if ($a[1] != 'tags')
				{
					$form_values['nodes'][$key]->taxonomy[$a[1]] = $value;
				}
				else
				{
					$form_values['nodes'][$key]->taxonomy[$a[1]][$a[2]] = $value;
				}
				unset($form_values['nodes'][$key]->$field);
			}
		}
	}
}