/*
 * jQuery simpleAccordion plugin
 * @author Jonas Weidler (jquery@jonas-weidler.de)
 * @version 0.1.1
 * @date July 16, 2010
 * @category jQuery plugin
 * @requires jQuery 1.4.2
 * @copyright (c) 2010 Jonas Weidler
 * @license CC Attribution-Share Alike 3.0 - http://creativecommons.org/licenses/by-sa/3.0/
 */

(function($){
	$.fn.extend({ 
		simpleAccordion: function(options) {
			var defaults = 
			{
				slideSpeed: 500,
				classOpened: 'active',
				elTitle: 'title',
				elContents: 'contents',
				event: 'click'
			};
			var options = $.extend(defaults, options);
			
			return this.each(function() {
								
				var opt = options;
				var obj = $(this);
				var objIndex = $("."+obj.attr("class")).index(obj);
				
				var objContents = $("."+opt.elContents, obj);
				var objTitle = $("."+opt.elTitle, obj);
				
				var running = false;
				
				// every title gets an anchor so we can scroll to it once
				// we slided down the contents-box
				objTitle.each(function(){
					$(this).prepend('<a class="anchor" name="acc-'+objIndex+'-set'+objTitle.index(this)+'" /><a class="trigger" href="#acc-'+objIndex+'-set'+objTitle.index(this)+'" />');
				});
				
				// simple fallback solution if smoothanchors is not loaded
				if ($.smoothAnchors == null) {
					$("a.trigger", objTitle).click(function(){
						window.location = $(this).attr("href");
					});
				}
				
				// setting a width prevents bumpy ending of slide transition
				// this is the only part that actually requires jQ 1.4 :-(
				var width = objContents.width();
				
				objContents.each(function(){
					//alert($(this).height());
				});
				
				objContents.hide();
				objContents.css("width", width);
				
				objTitle.css({
					cursor: "pointer"
				});
				
				objContents.hide();
				
				//
				objContents.each(function(){
					$(this).attr('rel', 'set-contents-'+objContents.index(this));
				});
				
				objTitle.bind(opt.event, function(event){
					var el = $(this);
					var closeOnly = false;
					$("."+opt.elContents+"."+opt.classOpened, obj).each(function(){
						if (!running) {
							//running = true;
							if (el.next().attr("rel") != $(this).attr("rel")) {
								$(this).slideUp(opt.slideSpeed).removeClass(opt.classOpened);
								objTitle.removeClass(opt.classOpened);
							}
							else {
								closeOnly = true;
								running = true;
								$(this).slideUp(opt.slideSpeed, function(){running = false;}).removeClass(opt.classOpened);
								objTitle.removeClass(opt.classOpened);
							}
						}
					});
					if (!running && !el.next().hasClass(opt.classOpened) && !closeOnly) {
						//running = true;
						el.next().slideDown(opt.slideSpeed, function(){
							$("a.trigger", el).click();
							//running = false;
						}).addClass(opt.classOpened);
						el.addClass(opt.classOpened);
					}
				});
				
			});
		}
	});
})(jQuery);
