/*
 *
 * 
 * by mathieu vilaplana mvilaplana@dfc-e.com
 * Designer ghyslain armand garmand@dfc-e.com
 * Modified by Dan Partac to only use select replacement
 *
 * Version 1.0 25.09.08
 * Version 1.1 06.08.09
 * Add event click on Checkbox and Radio
 * Auto calculate the size of a select element
 * Can now, disabled the elements
 * Correct bug in ff if click on select (overflow=hidden)
 * No need any more preloading !!
 * 
 ******************************************** */
 
(function($){
	var defaultOptions = {preloadImg:true};
	var ImgPreloaded = false;

	var PreloadHoverFocusImg = function(strImgUrl) {
		//guillemets to remove for ie
		strImgUrl = strImgUrl.replace(/^url\((.*)\)/,'$1').replace(/^\"(.*)\"$/,'$1');
		var imgHover = new Image();
		imgHover.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-hover.$1');
		var imgFocus = new Image();
		imgFocus.src = strImgUrl.replace(/\.([a-zA-Z]*)$/,'-focus.$1');				
	};

	
	/***************************
	  Labels
	***************************/
	var GetLabel = function(objfield){
		var selfForm = jQuery(objfield.get(0).form);
		var oLabel = objfield.next();
		if(!oLabel.is('label')) {
			oLabel = objfield.prev();
			if(oLabel.is('label')){
				var inputname = objfield.attr('id');
				if(inputname){
					oLabel = selfForm.find('label[for="'+inputname+'"]');
				} 
			}
		}
		if(oLabel.is('label')){return oLabel.css('cursor','pointer');}
		return false;
	};
	
	/* Hide all open selects */
	var HideSelect = function(oTarget){
		var ulVisible = jQuery('.SelectWrapper ul:visible');
		ulVisible.each(function(){
			var oSelect = jQuery(this).parents(".SelectWrapper:first").find("select").get(0);
			//do not hide if click on the label object associated to the select
			if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){jQuery(this).hide();}
		});
	};
	/* Check for an external click */
	var CheckExternalClick = function(event) {
		if (jQuery(event.target).parents('.SelectWrapper').length === 0) { HideSelect(jQuery(event.target)); }
	};

	/* Apply document listener */
	var AddDocumentListener = function (){
		jQuery(document).mousedown(CheckExternalClick);
	};	
			
	/* Add a new handler for the reset action */
	var Reset = function(f){
		var sel;
		jQuery('.SelectWrapper select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; jQuery('ul', jQuery(this).parent()).each(function(){jQuery('a:eq('+ sel +')', this).click();});});
	};
	
	/***************************
	  Select 
	 ***************************/	
	jQuery.fn.TransformSelect = function(){
		return this.each(function(index){
			var $select = jQuery(this);

			if($select.hasClass('Hidden')) {return;}
			if($select.attr('multiple')) {return;}

			var oLabel  =  GetLabel($select);
			/* First thing we do is Wrap it */
			var $wrapper = $select
				.addClass('Hidden')
				.wrap('<div class="SelectWrapper"></div>')
				.parent()
				.css({zIndex: 10-index})
			;
			
			/* Now add the html for the select */
			$wrapper.prepend('<div><span></span><a href="#" class="SelectOpen"></a></div><ul></ul>');
			var $ul = jQuery('ul', $wrapper).css('width',$select.width()).hide();
			/* Now we add the options */
			jQuery('option', this).each(function(i){
				var oLi = jQuery('<li><a href="#" index="'+ i +'">'+ jQuery(this).html() +'</a></li>');
				$ul.append(oLi);
			});
			
			/* Add click handler to the a */
			$ul.find('a').click(function(){
					jQuery('a.selected', $wrapper).removeClass('selected');
					jQuery(this).addClass('selected');	
					/* Fire the onchange event */
					if ($select[0].selectedIndex != jQuery(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = jQuery(this).attr('index'); $select[0].onchange(); }
					$select[0].selectedIndex = jQuery(this).attr('index');
					jQuery('span:eq(0)', $wrapper).html(jQuery(this).html());
					$ul.hide();
					return false;
			});
			/* Set the default */
			jQuery('a:eq('+ this.selectedIndex +')', $ul).click();
			jQuery('span:first', $wrapper).click(function(){jQuery("a.SelectOpen",$wrapper).trigger('click');});
			oLabel && oLabel.click(function(){jQuery("a.SelectOpen",$wrapper).trigger('click');});
			this.oLabel = oLabel;
			
			/* Apply the click handler to the Open */
			var oLinkOpen = jQuery('a.SelectOpen', $wrapper)
				.click(function(){
					//Check if box is already open to still allow toggle, but close all other selects
					if( $ul.css('display') == 'none' ) {HideSelect();} 
					if($select.attr('disabled')){return false;}

					$ul.slideToggle('fast', function(){					
						var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
						$ul.animate({scrollTop: offSet});
					});
					return false;
				})
			;

			// Set the new width
			var iSelectWidth = $select.outerWidth();
			var oSpan = $('span:first',$wrapper);
			var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
			$wrapper.css('width',newWidth);
			$ul.css('width',newWidth-0);
			oSpan.css({width:iSelectWidth});
		
			// Calculate the height if necessary, less elements that the default height
			//show the ul to calculate the block, if ul is not displayed li height value is 0
			$ul.css({display:'block',visibility:'hidden'});
			var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
			(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
			$ul.css({display:'none',visibility:'visible'});
			
		});
	};
	jQuery.fn.transform = function(options){
		var opt = jQuery.extend({},defaultOptions,options);
		
		/* each form */
		 return this.each(function(){
			var selfForm = $(this);
			if(selfForm.hasClass('done')) {return;}
			selfForm.addClass('done');
			
			
			if( jQuery('select', this).TransformSelect().length > 0 ){AddDocumentListener();}
			selfForm.bind('reset',function(){var action = function(){Reset(this);}; window.setTimeout(action, 10);});
			

			
			
		}); /* End Form each */
				
	};/* End the Plugin */

})(jQuery);

