/**
 * Collapsible plugin
 *
 * Copyright (c) 2010 Ramin Hossaini (www.ramin-hossaini.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.collapsible = function(selector, identifier) {
	
	//toggle the div after the header and set a unique-cookie
	jQuery(selector).click(function() {
		jQuery(this).next().slideToggle('fast', function() {
			if ( jQuery(this).is(":hidden") ) {
				jQuery.cookie(jQuery(this).prev().attr("id"), 'hide');
				jQuery(this).prev().children(".placeholder").removeClass("collapse").addClass("expand");
			}
			else {
				jQuery.cookie(jQuery(this).prev().attr("id"), 'show');
				jQuery(this).prev().children(".placeholder").removeClass("expand").addClass("collapse");
			}
		});
		return false;
	}).next();

	
	//show that the header is clickable
	jQuery(selector).hover(function() {
		jQuery(this).css("cursor", "pointer");
	});

	/*
	 * On document.ready: should the module be shown or hidden?
	 */
	var idval = 0;	//increment used for generating unique ID's
	jQuery.each( jQuery(selector) , function() {

		jQuery(jQuery(this)).attr("id", "module_" + identifier + idval);	//give each a unique ID

		if ( !jQuery(jQuery(this)).hasClass("collapsed") ) {
			jQuery("#" + jQuery(this).attr("id") ).append("<span class='placeholder collapse'></span>");
		}
		else if ( jQuery(jQuery(this)).hasClass("collapsed") ) {
			//by default, this one should be collapsed
			jQuery("#" + jQuery(this).attr("id") ).append("<span class='placeholder expand'></span>");
		}
		
		//what has the developer specified? collapsed or expanded?
		if ( jQuery(jQuery(this)).hasClass("collapsed") ) {
			jQuery("#" + jQuery(this).attr("id") ).next().hide();
			jQuery("#" + jQuery(this).attr("id") ).children("span").removeClass("collapse").addClass("expand");
		}
		else {
			jQuery("#" + jQuery(this).attr("id") ).children("span").removeClass("expand").addClass("collapse");
		}

	
		if ( jQuery.cookie(jQuery(this).attr("id")) == 'hide' ) {
			jQuery("#" + jQuery(this).attr("id") ).next().hide();
			jQuery("#" + jQuery(this).attr("id") ).children("span").removeClass("collapse").addClass("expand");
		}
		else if ( jQuery.cookie(jQuery(this).attr("id")) == 'show' ) {
			jQuery("#" + jQuery(this).attr("id") ).next().show();
			jQuery("#" + jQuery(this).attr("id") ).children(".placeholder").removeClass("expand").addClass("collapse");
		}
		

		idval++;
	});

};
