/*
 * nice dropdowns
 * (c) 2010-06 Björn Hampe / YOC AG
 * version: 0.1.7
 * for YOC Group
 */

(function($) {
  /*** plugin definition ***/
	jQuery.fn.nicedropdowns = function($$options) {
	  // -- build main options before element iteration
	  var $settings = $.extend({}, $.fn.nicedropdowns.defaults, $$options);
	  var iDDCounter = $(this).length + 100; // for z-index
		/*** iterate each matched element ***/
		$(this).each(function() {
			var $this = $(this);
	    // build element specific options
			var settings = $.metadata ? $.extend({}, $settings, $this.metadata()) : $settings;
			// go on with the crucial things
			var mySelectElem = $(this);
			mySelectElem.wrap('<div id="nicedropdown_'+mySelectElem.attr('id')+'" class="nicedropdown" />');
			$('#nicedropdown_'+mySelectElem.attr('id')).addClass(mySelectElem.attr('class').replace(/{.*}/, '')).css('z-index',iDDCounter);
			var myElem = mySelectElem.parent('.nicedropdown');
			myElem.prepend('<div class="nicedropdown-arrow" />');
			mySelectElem.hide();
			myElem.prepend('<div class="nicedropdown-info">'+$('#'+$(this).attr('id')+' option:selected').text()+'</div>');
			myElem.children('.nicedropdown-arrow').html(((settings.showFlags)?'<img src="'+settings.flagPath+(($(this).val()!='-')?$(this).val():settings.defaultFlag)+'.png" width="16" height="11" alt="" border="0" /> ':''));

			// more than one option
			if (myElem.find('option').length > 1) {
				myElem.prepend('<div class="nicedropdown-field" />');
				// add each option to the div list
				myElem
					.find('option')
					.each( function() {
						if ($(this).val() != '-' || (settings.removeSelectedFromList && !$(this).attr('selected'))) {
							myElem
								.children('.nicedropdown-field')
								.append(
									'<div class="nicedropdown-row">'+
									'<input type="hidden" value="'+$(this).val()+'" />'+
									((settings.showFlags)?'<img src="'+settings.flagPath+$(this).val()+'.png" width="16" height="11" alt="" border="0" /> ':'') +
									$(this).text()+
									'</div>'
								);
						}
					});
				$('.nicedropdown-row')
					.mouseenter(function() { $(this).addClass('nicedropdown-row-hover'); } )
					.mouseleave(function() { $(this).removeClass('nicedropdown-row-hover'); } );

				// bind events to dropdown
				myElem
					// -- prevent document mouseup event
					.mouseup( function(e) { e.stopPropagation(); } )
					.mousedown( function(e) {
						// if dropdown open:
						if ($(this).children('.nicedropdown-field').css('display') == 'block') {
							// -- close dropdown
							$(this).children('.nicedropdown-field').stop(true, true).slideUp(50);
							// -- reset arrow
							$(this).children('.nicedropdown-arrow').css('backgroundImage', myElem.find('.nicedropdown-arrow').css('backgroundImage').replace(/-up/, "-down"));
						// -- ... else:
						} else {
							// hide all other dropdowns:
							$('.nicedropdown-field').hide();
							// -- ... and reset arrows:
							$(document).find('.nicedropdown-arrow').css('backgroundImage', myElem.find('.nicedropdown-arrow').css('backgroundImage').replace(/-up/, "-down"));
							// -- open dropdown
							$(this).children('.nicedropdown-field').stop(true, true).slideDown(50);
							// -- set arrow
							$(this).children('.nicedropdown-arrow').css('backgroundImage', myElem.find('.nicedropdown-arrow').css('backgroundImage').replace(/-down/, "-up"));
						}
					});

				// bind events to dropdown rows
				myElem
					.find('.nicedropdown-row')
					.mousedown( function(e) { e.stopPropagation(); /* prevent dropdown mousedown event */ } )
					.mouseup( function(e) {
						// prevent dropdown mouseup event
						e.stopPropagation();

						// add previous to list and remove current from list

/*						console.log('remove from list and add previous selected');
						console.log('previous: ' + $(this).parents('.nicedropdown').find('.nicedropdown-info').text());
						console.log('current: ' + $(this).find('input').val() + ' - ' + jQuery.trim($(this).text()));
						console.log(mySelectElem.find('option'));
						console.log($('#'+mySelectElem.attr('id')).val(jQuery.trim( $(this).parents('.nicedropdown').find('.nicedropdown-info').text() )).val());
*/
						$('#'+mySelectElem.attr('id')).val($(this).find('input[type=hidden]').val()).change();
						myElem.find('.nicedropdown-info').html($(this).text());
						myElem.find('.nicedropdown-arrow').html((settings.showFlags)?'<img src="'+settings.flagPath+$(this).find('input').val()+'.png" width="16" height="11" alt="" border="0" />':'');
						closeDD(e, myElem);
					});
				// -- if select field has onchange event, fire form
				if (mySelectElem.attr('onchange')) {
					mySelectElem
						.change( function() {
							mySelectElem.attr('onchange');
							return false;
						});
				}
			}

			/*** auto set elements width ***/
			var myArrow   = myElem.find('.nicedropdown-arrow');
			var myDDInfo  = myElem.find('.nicedropdown-info');
			var myDDField = myElem.find('.nicedropdown-field');

			if (settings.maxWidth > 0) {
				var iArrowWidth = parseInt(myArrow.outerWidth());
				var iMaxWidth = parseInt(settings.maxWidth);
				var sizes = {
					infopadding: (parseInt(myDDInfo.outerWidth()) - parseInt(myDDInfo.width())) || 0,
					fieldpadding: (parseInt(myDDField.outerWidth()) - parseInt(myDDField.width())) || 0
				}
				myElem.width(iMaxWidth);
				myDDInfo.width(iMaxWidth - sizes.infopadding - iArrowWidth -1);
				myDDField.width(iMaxWidth - (sizes.fieldpadding - settings.fieldWidthCorrection) - iArrowWidth).hide();
			} else {
				var maxWidthField = ( (parseInt(myDDInfo.width()) || 0) > (parseInt(myDDField.width()) || 0) )
					? '.nicedropdown-info'
					: '.nicedropdown-field';
				var iArrowWidth = parseInt(myArrow.outerWidth());
				var iMaxWidth = parseInt(myElem.find(maxWidthField).outerWidth());
				var sizes = {
					infopadding: (parseInt(myDDInfo.outerWidth()) - parseInt(myDDInfo.width())) || 0,
					fieldpadding: (parseInt(myDDField.outerWidth()) - parseInt(myDDField.width())) || 0,
					infoborder:
					(parseInt(myDDInfo.css('borderLeftWidth'))) ?
						parseInt(myDDInfo.css('borderLeftWidth')) : 0 +
					(parseInt(myDDInfo.css('borderRightWidth'))) ?
						parseInt(myDDInfo.css('borderRightWidth')) : 0,
					fieldborder:
					(parseInt(myDDField.css('borderLeftWidth'))) ?
						parseInt(myDDField.css('borderLeftWidth')) : 0 +
					(parseInt(myDDField.css('borderRightWidth'))) ?
						parseInt(myDDField.css('borderRightWidth')) : 0
				}
				var maxborder = (sizes.infoborder > sizes.fieldborder)?sizes.infoborder:sizes.fieldborder;
				myElem.width(iMaxWidth + (sizes.fieldpadding - maxborder) + iArrowWidth);
				myDDInfo.width(iMaxWidth-sizes.infopadding);
				myDDField.width(iMaxWidth-(maxborder-settings.fieldWidthCorrection)).hide();
			}

			iDDCounter--;

	  });

	  function closeDD(evt, elm) {
			// -- close dropdown
			$(elm).children('.nicedropdown-field').stop(true, true).slideUp(50);
			// -- reset arrow
			$(elm).children('.nicedropdown-arrow').css('backgroundImage', elm.find('.nicedropdown-arrow').css('backgroundImage').replace(/-up/, "-down"));
	  }

		/*** hide all select boxes if click on body ***/
		$(document).mouseup(
			function() {
				if ($(this).find('.nicedropdown-field').css('display') == 'block') {
					// -- close all dropdowns
					$(this).find('.nicedropdown-field').stop(true, true).slideUp(10);
					// -- reset arrows
					$(this).find('.nicedropdown-arrow').css('backgroundImage', $(this).find('.nicedropdown-arrow').css('backgroundImage').replace(/-up/, "-down"));
				}
			}
		); // click
  } // each function

	/*** plugin defaults ***/
  jQuery.fn.nicedropdowns.defaults = {
    showFlags: false,
    defaultFlag: 'de',
		flagPath: '/images/flags/',
		maxWidth: 0,
		fieldWidthCorrection: 0,
		removeSelectedFromList: false
  };
})(jQuery);

