/*
Copyright © 2010 by Joran Quinten

web: http://www.cre8ion.com
email: joran@cre8ion.com

Free for non-commercial use

Technical notes:

Create dropdowns like this:

   <div class="dropdown" id="rDD">
   	<div class="contents">
   		<ul>
   			<li><a href="#1" title="option 1">option 1</a></li>
   			<li><a href="#2" title="option 2">option 2</a></li>
   			<li><a href="#3" title="option 3">option 3</a></li>
   		</ul>
   	</div>
   	<div class="controls"></div>
   	<label class="switch">Select an option</label>
   </div>

*/

jQuery.fn.richDropdown = function(options)
{
		var defaults = {
			slideSpeed: 500
		};
		var opts = jQuery.extend(defaults, options);

		var mouseInsideDropdown = false;

  return this.each(function() {
    var e = jQuery(this);
		  var o = jQuery.meta ? jQuery.extend({}, opts, e.data()) : opts;
    var targetInput = e.attr('id').toString();

    // Emulate "selected" state
    if ( jQuery('#'+targetInput+'Input').val() != '' )
    {
       // Find selected value in list
       targetHref = '#'+jQuery('#'+targetInput+'Input').val().toString();
       // Add active class
       jQuery('a[href='+targetHref+']').addClass('active');
       // Write switch contents
       e.find('.switch').html( jQuery('a[href='+targetHref+']').attr('title') );
    }

    // Init dropdown
    e.children('.switch').addClass('clickable');
			 e.children('.switch').bind({
			 	click: function(){ toggleDropdown( jQuery(this).parent() ) }
			 });
    // Setup collapse event
    e.hover(function(){	mouseInsideDropdown = true; },
		          function(){ mouseInsideDropdown = false; });
    jQuery('body').mouseup(function(){	if(!mouseInsideDropdown) hideDropdown() });

    // Click action
    jQuery(this).find('li').bind({
  				click: function(){
  					var thisLink = jQuery(this).children('a');

  					jQuery(this).siblings().children('a').removeClass('active');
  					thisLink.addClass('active');
  					jQuery(this).parents('.dropdown').find('.switch').html( thisLink.attr('title').replace('#','') );
       // Copy selected value to input
       jQuery('#'+targetInput+'Input').val( thisLink.attr('href').replace('#','') );

  					return false;
  				}
  			});

     function activeItem(eItem,eTarget,value)
     {
     }

  			function toggleDropdown(e)
  			{
  				var eHeight = parseInt(e.css('height').replace('px',''));
  				if (eHeight < 130){
  					e.animate({ height: 130},o.slideSpeed,function(){
  					e.children('.switch').addClass('open');
  					});
  				}else{
  					e.animate({ height: 27 },(o.slideSpeed/2),function(){
  					e.children('.switch').removeClass('open');
  					});
  				}
  			}

  			function hideDropdown()
  			{
  				e.each(function(){
  					jQuery(this).animate({ height: 27 },(o.slideSpeed/2),function(){
  					jQuery(this).children('.switch').removeClass('open');
  					});
  				});
  			}

  });
}