/**
 * JavaScript file for Element: Toggler
 * Adds slide in and out functionality to elements based on an elements value
 *
 * @package    NoNumber! Elements
 * @version    v1.0.0
 *
 * @author     Peter van Westen <peter@nonumber.nl>
 * @link       http://www.nonumber.nl
 * @copyright  Copyright (C) 2009 NoNumber! All Rights Reserved
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

var togglers = '';

window.addEvent( 'domready', function() {
	initTogglers();
});

function initTogglers()
{
	f = document.forms['adminForm'];
	togglers = $$('.toggler');
	togglers.each( function( toggler, i ) {
		toggler.fx = new Fx.Slide( toggler );
		ids = toggler.id.split( ' ' );
		toggler.values = new Array();
		for ( var i = 0; i < ids.length; i++ ) {
			toggler.values[i] = ( ids[i].split( '.' ) )[1];
		}
		groupname = ( ids[0].split( '.' ) )[0];
		toggler.group = f['params['+groupname+']'];
		setOnchange( toggler.group );
		if( in_array( groupActive( toggler.group ), toggler.values ) ) {
			toggler.fx.show();
		} else {
			toggler.fx.hide();
		}
		toggler.parentNode.parentNode.style.padding = '0px';
	});
}

function toggle( group )
{
	togglers.each( function( toggler, i ) {
		if ( !group || group == toggler.group ) {
			parentSlider = toggler.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
			if ( parentSlider.className == 'jpane-slider content' ) {
				parentSlider.style.height = 'auto';
			} else {
				parentDiv = parentSlider.parentNode;
				parentDiv.style.height = 'auto';
				parentSlider = parentDiv.parentNode.parentNode.parentNode.parentNode.parentNode;
				parentSlider.style.height = 'auto';
			}
			if( in_array( groupActive( toggler.group ), toggler.values ) ) {
				toggler.fx.slideIn();
			} else {
				toggler.fx.slideOut();
			}
		}
	});
}

function groupActive( group )
{
	active = new Array();
	for ( var i = 0; i < group.length; i++ ) {
		if ( group[i].checked || group[i].selected ) {
			active = group[i].value;
		}
	}
	return active;
}

function setOnchange( group )
{
	if( group.tagName == 'SELECT' ) {
		$(group).addEvent( 'change', function(event) { toggle( group ); });
	} else {
		for ( var i = 0; i < group.length; i++ ) {
			$(group[i] ).addEvent( 'change', function(event) { toggle( group ); });
		}
	}
}
function in_array( needle, haystack ) {
    for (key in haystack) {
        if (haystack[key] == needle) {
            return true;
        }
    }
    return false;
}