/*
 * ExpandChild - Expand/Hide Child
 * Example: Assign div with class "expandchild".  First child element is the title.  
 *			Subsequent child elements are expandable elements.
 *			<div class="expandchild">
 *				<h2>Title</h2>
 *				<ul><li>Expandable elements</li></ul>
 *			</div>
 * Version: 1.0a (08/29/09)
 * Copyright (c) 2009 Zinj Guo
 * Licensed under the MIT License: http://en.wikipedia.org/wiki/MIT_License
 * Requires: jQuery v1.3+
*/

;(function($) {
	$.expandchild = function(options){
		//settings
		$.expandchild.settings = $.extend($.expandchild.defaults, options);		
		var selector = $.expandchild.settings.selector;
		
		$(selector).each(function(){
			if($.expandchild.settings.carat){
				if(!$(this).children().eq(1).is(":hidden")){
					$(this).children().eq(0).prepend("<span class='ui-icon ui-icon-triangle-1-e ui-icon-triangle-1-s'>Collapse</span>");
				}else{
					$(this).children().eq(0).prepend("<span class='ui-icon ui-icon-triangle-1-e'>Collapse</span>");
				}
			}
			
			$(this).children().eq(0).click(function(evt){
				$.expandchild.toggle(this);
				evt.preventDefault();				
			});
		
			
			if($.expandchild.settings.hideAtStart){
				$(this).children().filter(function(index){
					return index == 1;
					}).css({"display": "none"});
			}
		});
	};
	
	$.expandchild.toggle = function(el){
		$(el).siblings().each(function(){
			$(this).slideToggle(100);
		});
		if($.expandchild.settings.carat){
			$(el).children().eq(0).toggleClass('ui-icon-triangle-1-s');
		}
	}
	
	$.expandchild.expand_all_toggle = function(el){
		var selector = $.expandchild.settings.selector;
		if(!$.expandchild.all_expanded){
			$(selector).each(function(){
				$(this).children().eq(1).show();
				if($.expandchild.settings.carat){
					$(this).children().eq(0).children().eq(0).addClass('ui-icon-triangle-1-s');
				}				
			})
			$.expandchild.all_expanded = true;			
		}else{
			$(selector).each(function(){
				$(this).children().eq(1).hide();
				if($.expandchild.settings.carat){
					$(this).children().eq(0).children().eq(0).removeClass('ui-icon-triangle-1-s');
				}
			})
			$.expandchild.all_expanded = false;
		}
	}
	
	$.expandchild.defaults = {
		selector : ".expandchild",
		carat : true,
		hideAtStart: true
	}
	
	$.expandchild.all_expanded = false;
	
	$(document).ready(function(){
		$.expandchild({hideAtStart : false});
	});
})(jQuery)