/**
 * jQuery spraudnis, kurš domāts select izvēlņu stilošanai
 *
 * @copyright SIA Mendo 2011 (http://mendo.lv)
 */

jQuery('body').live('click', function(event) {
	var selects = jQuery('.styleable-select ul');

	if (jQuery(event.target).parents('.styleable-select')) {
		var current_select = jQuery(event.target).parents('.styleable-select').find('ul');
		selects = selects.not(current_select);
	}

	if (selects.length) {
		selects.toggleStyleableSelect(false);
	}
});

jQuery.fn.toggleStyleableSelect = function(toggle) {
	if (toggle) {
		jQuery(this).show().parent().addClass('open');

		if (jQuery(this).height() > 220) {
			jQuery(this).height(220);
		}
	} else {
		jQuery(this).hide().parent().removeClass('open');
	}

	return jQuery(this);
}

jQuery.fn.styleableSelect = function() {
	return this.each(function() {
		if ($(this).siblings('div').hasClass('styleable-select')) {
			return false;
		}

		var content = jQuery('<div class="styleable-select"><div class="active-item"><span></span></div></div>');

		content.append(jQuery('<ul/>'));

		jQuery(this).click(function() {
			jQuery(this).prev('.styleable-select').find('.active-item').click();
			return false;
		}).find('option').each(function() {
			var value = jQuery(this).attr('value');
			var text = jQuery(this).text();
			content.children('ul').append('<li data-value="'+ value +'">' + text + '</li>');
		});

		content.find('.active-item').click(function() {
			jQuery(this).parents('.styleable-select').find('ul').toggleStyleableSelect(true);
		});

		content.find('li').click(function() {
			var styleable_select = jQuery(this).parents('.styleable-select');
			styleable_select.find('.active-item span').html(jQuery(this).text());
			styleable_select.next('select').val(jQuery(this).attr('data-value'));
			styleable_select.next('select').trigger('change');

			styleable_select.find('ul').toggleStyleableSelect(false);
		});

		content.find('li[data-value="' + jQuery(this).val() + '"]').click();

		content.width(jQuery(this).width() - 5);

		jQuery(this).hide().before(content);
	});
}
