(function ($) {
	'use strict';

	function parseColor(value) {
		if (!value) return { r: 0, g: 0, b: 0, a: 1 };
		value = value.trim();
		if (value === 'transparent') return { r: 0, g: 0, b: 0, a: 0 };
		var m = value.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*(0|0?\.\d+|1(?:\.0)?))?\s*\)/i);
		if (m) return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? parseFloat(m[4]) : 1 };
		var hex = value.replace('#', '');
		if (hex.length === 3) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
		if (hex.length === 6) {
			var num = parseInt(hex, 16);
			return { r: (num >> 16) & 255, g: (num >> 8) & 255, b: num & 255, a: 1 };
		}
		return { r: 0, g: 0, b: 0, a: 1 };
	}

	function toCssColor(c) {
		var a = typeof c.a === 'number' ? c.a : 1;
		if (a >= 1) {
			return 'rgb(' + c.r + ',' + c.g + ',' + c.b + ')';
		}
		return 'rgba(' + c.r + ',' + c.g + ',' + c.b + ',' + a.toFixed(2) + ')';
	}

	function init($input) {
		if ($input.data('alpha-init')) return;
		$input.data('alpha-init', true);

		$input.wpColorPicker({
			change: function (event, ui) {
				var color = ui.color.toString();
				$input.val(color).trigger('change');
				updateSlider($input, color, ui.color);
			},
			clear: function () {
				$input.val('').trigger('change');
				updateSlider($input, '');
			}
		});

		addSlider($input);
		updateSlider($input, $input.val());
	}

	function addSlider($input) {
		var $container = $input.closest('.wp-picker-container');
		if (!$container.length || $container.find('.alpha-slider-wrap').length) return;

		var $wrap = $('<div class="alpha-slider-wrap"><label>Opacity</label><input type="range" min="0" max="100" value="100"></div>');
		var $inputWrap = $container.find('.wp-picker-input-wrap');
		if ($inputWrap.length) {
			$inputWrap.after($wrap);
		} else {
			$container.append($wrap);
		}

		$wrap.find('input[type="range"]').on('input change', function () {
			var current = parseColor($input.val());
			current.a = parseInt(this.value, 10) / 100;
			var css = toCssColor(current);
			$input.wpColorPicker('color', css);
			$input.val(css).trigger('change');
		});
	}

	function updateSlider($input, value, uiColor) {
		var $container = $input.closest('.wp-picker-container');
		var $range = $container.find('.alpha-slider-wrap input[type="range"]');
		if (!$range.length) return;
		var alpha = 1;
		if (uiColor && typeof uiColor._alpha === 'number') {
			alpha = uiColor._alpha;
		} else {
			var color = parseColor(value);
			alpha = typeof color.a === 'number' ? color.a : 1;
		}
		$range.val(Math.round(alpha * 100));
	}

	$(function () {
		$('.alpha-color-control').each(function () {
			init($(this));
		});
		$(document).on('input change', '.alpha-color-control', function () {
			updateSlider($(this), $(this).val());
		});
		$(document).on('click', '.wp-color-result', function () {
			var $input = $(this).closest('.wp-picker-container').find('.alpha-color-control');
			if ($input.length) init($input);
		});
	});
})(jQuery);
