/**
 * jQuery Select Replace plugin
 * @name jquery.selectreplace.js
 * @author Aaron Vanderzwan - http://www.aaronvanderzwan.com/
 * @version 0.1
 * @date May 15, 2009
 * @category jQuery plugin
 * Developed for Steelcase.com
 *
 */

(function($) {
	
  $.fn.selectReplace = function(options) {
	
	  var opts = jQuery.extend({
			addClear: true,
	    clearText: 'Clear',
			hideSubmit: true
	  }, options);
		
		
		jQuery(this).hide();
		if(opts.hideSubmit){
			jQuery(this).next('input[type=submit]').hide();	
		}
		
		
		var count = this.length;
		this.each(function(i){
			var select = this;
			jQuery(select).wrap('<li class="selectReplace sr-'+i+' '+jQuery(select).attr('class').replace('selectReplace', '')+'"></li>');
			jQuery('.sr-'+i).append('<ul class="sList"></ul>');
			
			if(i==count-2){ // If this is the last select, add 'last' class to li (-2 because of width)
				jQuery('.sr-'+i).addClass('last');
			}
			
			jQuery(select).children('option').each(function(j){
				var option = this;
				if (j==0) { // First option is set to anchor outside of list and inside is hidden
					jQuery('.sr-'+i).prepend('<a href="" class="head">'+jQuery(option).html()+'</a>');
					jQuery('.head').data('originalValue',jQuery(option).html());
				}else{
					// Write li and anchor
					jQuery('.sr-'+i+' > ul').append('<li class="or-'+j+'" title="'+$(option).val()+'"><a href="">'+$(option).html()+'</a></li>');
					// Write associated widths to correct ul
					jQuery('.sr-'+i+' li.or-'+j).attr('alt',jQuery(option).attr('label'));
				}
			});
			
			// Add 'clear' link
			if(opts.addClear){
				jQuery('.sr-'+i).children('.sList').append('<li><a href="" class="reset">'+opts.clearText+'</a></li>');
			}
		});

		// Wrap all with selectors
		jQuery('.selectReplace').wrapAll('<ul class="selectors"></ul>');
		
		
		// Add 'over' class on hover for those with js.
		jQuery('ul.selectors li').mouseover(makeTall).mouseleave(makeShort);
			
		// Onclick Actions
		// All but reset click
		jQuery('.sList a').not('.reset').click(function(){
			var $parent = getParentLink(this);
			$parent.html(jQuery(this).html());
		});
		// Only reset click
		jQuery('.reset').click(function(){
			// Find parent
			var $parent = getParentLink(this);
			// Set parent html to it's original value
			$parent.html($parent.data('originalValue'));
			return false;
		});
		// All clicks
		jQuery('.sList a').click(function(){
			$(this).trigger({ type:"mouseleave"});
		});

		
		// Traverse a < li < ul < ul > a.head
		function getParentLink(a){
			var b = jQuery(a).parent().parent().parent().children('a.head');
			return b;
		}
    
		function makeTall(){$(this).addClass('over');}
		function makeShort(){$(this).removeClass('over')}
		
    // Private function for debugging
    function debug($obj) {
      if (window.console && window.console.log) {
        window.console.log($obj);
      }
    }
  };
})(jQuery);
