(function ($) {
"use strict";
	if (!window.wpfAdminPagePro) {
		window.wpfAdminPagePro = function () {
			var WpfAdminPage = window.wpfAdminPage;

			WpfAdminPage.constructor.prototype.initPro = (function () {
				var	isWaitLoad = typeof WpfAdminPage.wpfWaitLoad != 'undefined';
				if(isWaitLoad) WpfAdminPage.wpfWaitLoad = true;
				wpfEventsOptionsPro();
				wpfEventsDesingPro();
				if(isWaitLoad) WpfAdminPage.wpfWaitLoad = false;
				jQuery(".wpfProOption").hide();

				function wpfEventsOptionsPro() {
					jQuery('#row-tab-options select[name="settings[display_page_list][]').chosen({ width:"95%" });
				}

				function wpfEventsDesingPro() {
					var optionsContainer = jQuery('#row-tab-options');
					jQuery('#wpfSelectLoaderButton').on('click', function(e){
						e.preventDefault();
						var $button = jQuery(this),
							$input = $button.parent().find('input'),
							$preview = jQuery('.wpfIconPreview'),
							$iconName = optionsContainer.find('input[name="settings[filter_loader_icon_name]"]'),
							_custom_media = true;
						wp.media.editor.send.attachment = function(props, attachment){
							wp.media.editor._attachSent = true;
							if(_custom_media) {
								var selectedUrl = attachment.url,
									imgWidth = attachment.width,
									imgHeight = attachment.height;
								if(props && props.size && attachment.sizes && attachment.sizes[props.size] && attachment.sizes[props.size].url) {
									var imgSize = attachment.sizes[props.size];
									selectedUrl = imgSize.url;
									imgWidth = imgSize.width;
									imgHeight = imgSize.height;
								}
								$input.val('background-image:url('+selectedUrl+');width:'+imgWidth+'px;height:'+imgHeight+'px;');
								$iconName.val('custom');
								if ($preview.length) {
									$preview.html('<div class="woobewoo-filter-loader wpfCustomLoader"></div>');
									$preview.find('.woobewoo-filter-loader').css({'background-image': 'url('+selectedUrl+')', 'width': imgWidth+'px', 'height': imgHeight+'px'});
								}
							} else {
								return _orig_send_attachment.apply( this, [props, attachment] );
							}
						};
						wp.media.editor.insert = function(html) {
							if(_custom_media) {
								if(wp.media.editor._attachSent) {
									wp.media.editor._attachSent = false;
									return;
								}
								if(html && html != "") {
									var selectedUrl = $(html).attr('src');
									if(selectedUrl) {
										$input.val('background-image:url('+selectedUrl+');');
										$iconName.val('custom');
										if($preview.length) {
											$preview.html('<div class="woobewoo-filter-loader wpfCustomLoader"></div>');
											$preview.find('.woobewoo-filter-loader').css({'background-image': 'url('+selectedUrl+')'});
										}
									}
								}
							}
						};
						wp.media.editor.open($button);
						return false;
					});
					var hideButtons = optionsContainer.find('select[name^="settings[display_hide_button"]');
					hideButtons.on('change', function () {
						var textSettings = optionsContainer.find('input[name="settings[hide_button_hide_text]"], input[name="settings[hide_button_show_text]"]').closest('.settings-value'),
							isShow = false;
						hideButtons.each(function(){
							if(jQuery(this).val() != 'no') isShow = true;
						});
						if(isShow) textSettings.removeClass('wpfHidden');
						else textSettings.addClass('wpfHidden');
					});

					var designContainer = jQuery('#row-tab-design');

					designContainer.find('.wpfCopyStyles').on('click', function() {
						var forCopy = jQuery(this).attr('data-style'),
							selector = 'div[data-style="'+forCopy+'"] ';
						jQuery('.wpfFiltersTabContents').find(selector + 'input, ' + selector + 'select').each(function() {
							var $this = jQuery(this),
								name = $this.attr('name');
							if (typeof name != 'undefined' && name.length) {
								var hover = jQuery('.wpfFiltersTabContents ' + this.nodeName + '[name="'+name.slice(0, -1)+'_hover]"]');
								if(hover.length == 1){
									if(hover.hasClass('woobewoo-color-result-text')) hover.closest('.woobewoo-color-picker').find('.woobewoo-color-result').wpColorPicker('color', $this.val());
									else hover.val($this.val());
									hover.trigger('wpf-change');
								}
							}
						});
						WpfAdminPage.getPreviewAjax();
						return false;
					});

					jQuery('[name="settings[filter_loader_icon_color]"]').on('input change',function(){
		            	var color = jQuery(this).val();
		            	jQuery('.woobewoo-filter-loader').css({color:color});
					}).trigger('change');

					jQuery('.applyLoaderIcon').on('click', function(e){
						e.preventDefault();
						var loaderSettings = {};

						jQuery('input[data-loader-settings="1"]').each(function(){
							var $this = jQuery(this);
							loaderSettings[$this.attr('name').replace('settings[', '').replace(']', '')] = ($this.attr('type') == 'checkbox' ? ($this.is(':checked') ? 1 : 0) : $this.val());
						});

						jQuery.sendFormWpf({
							data: {
								mod: 'woofilterpro',
								action: 'applyLoader',
								settings: loaderSettings,
								id: jQuery('#wpfFiltersEditForm').attr('data-table-id')
							},
							onSuccess: function(res) {
								if(!res.error && res.data.message) {
									jQuery.sNotify({
										'icon': 'fa fa-check',
										'content': ' <span> '+res.data.message+'</span>',
										'delay' : 2500
									});
								}
							}
						});
					});
				}
			});

			WpfAdminPage.constructor.prototype.setSkinColor = (function (skin, color, withLabels) {
				var _this = this.$obj,
					dark = _this.lightenDarkenColor(color, -40),
					darker = _this.lightenDarkenColor(color, -80),
					light = _this.lightenDarkenColor(color, 50),
					style = '';
				switch(skin) {
					case 'flat':
						style += '.irs-bar,.irs-from,.irs-to,.irs-single{background-color:'+color+'!important;border-color:'+color+'!important;}';
						style += '.irs-handle > i:first-child{background-color:'+dark+'!important;}';
						style += '.irs-handle:hover > i:first-child{background-color:'+darker+'!important;}';
						style += '.irs-from:before,.irs-to:before,.irs-single:before{border-top-color:'+color+'!important;}';
						break;
					case 'big':
					case 'circle':
						style += '.irs-bar{background-color:'+light+'!important;border-color:'+color+'!important;background:linear-gradient(to bottom, #ffffff 0%, '+color+' 30%, '+light+' 100%)!important;}';
						style += '.irs-from,.irs-to,.irs-single{background-color:'+color+'!important;background:linear-gradient(to bottom, '+color+' 0%, '+dark+' 100%)!important;}';
						style += '.irs-grid-text{color:'+color+'!important;}';
						style += '.irs-grid-pol{background-color:'+color+'!important;}';
						break;
					case 'rail':
						style += '.irs-bar{background-color:'+light+'!important;border-color:'+color+'!important;background:linear-gradient(to bottom, #ffffff 0%, '+color+' 30%, '+light+' 100%)!important;}';
						style += '.irs-grid-text{color:'+color+'!important;}';
						style += '.irs-grid-pol{background-color:'+color+'!important;}';
						break;
					case 'modern':
						style += '.irs-bar{background-color:'+color+'!important;border-color:'+color+'!important;background:linear-gradient(to bottom, '+color+' 0%, '+dark+' 100%)!important;}';
						style += '.irs-from,.irs-to,.irs-single{background-color:'+color+'!important;}';
						style += '.irs-from:before,.irs-to:before,.irs-single:before{border-top-color:'+color+'!important;}';
						break;
					case 'sharp':
						style += '.irs-bar{background-color:'+light+'!important;}';
						style += '.irs-from,.irs-to,.irs-single{background-color:'+color+'!important;border-color:'+color+'!important;}';
						style += '.irs-from:before,.irs-to:before,.irs-single:before{border-top-color:'+color+'!important;}';
						style += '.irs-handle{background-color:'+color+'!important;}';
						style += '.irs-handle > i:first-child{border-top-color:'+color+'!important;}';
						style += '.irs-max,.irs-min{background-color:'+dark+'!important;}';
						break;
					case 'round':
					case 'square':
					case 'compact':
						style += '.irs-bar,.irs-from,.irs-to,.irs-single{background-color:'+color+'!important;border-color:'+color+'!important;}';
						style += '.irs-from:before,.irs-to:before,.irs-single:before{border-top-color:'+color+'!important;}';
						style += '.irs-handle{border-color:'+color+'!important;}';
						break;
					case 'trolley':
						style += '.irs-from:before,.irs-to:before,.irs-single:before{border-top-color:'+color+'!important;}';
						style += '.irs-bar {background-color:'+color+'!important;border-color:'+dark+'!important;}';
						break;
				}
				if(!withLabels) style += '.irs {margin-top:-20px}';
				jQuery('#wpfPriceStyle').html(style);
				jQuery('input[name="f_skin_css"]').val(style);
			});

			WpfAdminPage.constructor.prototype.lightenDarkenColor = (function (col, amt) {
				var usePound = false;
				if(col[0] == "#") {
					col = col.slice(1);
					usePound = true;
				}
	 			var num = parseInt(col, 16),
					r = (num >> 16) + amt,
					b = ((num >> 8) & 0x00FF) + amt,
					g = (num & 0x0000FF) + amt;
				if(r > 255) r = 255;
				else if(r < 0) r = 0;
				if(b > 255) b = 255;
				else if(b < 0) b = 0;
				if(g > 255) g = 255;
				else if(g < 0) g = 0;
				var res = (g | (b << 8) | (r << 16)).toString(16);
				return (usePound?"#":"") + '0'.repeat(6 - res.length) + res;
			});

			WpfAdminPage.constructor.prototype.eventsFiltersPro = (function ($filter, settings) {
				var _this = this.$obj,
					filterId = $filter.attr('data-filter');

				switch (filterId) {
					case 'wpfAttribute':
                    	_this.initAttributeColorFilter($filter, settings);
                    	_this.initSliderFilter($filter, settings);
						break;
					case 'wpfPrice':
						_this.initSliderFilter($filter, settings);
						break;
						
					case 'wpfSearchText':
						var searchBy = $filter.find('input[name="f_search_by"]').val(),
							fields = $filter.find('.wpfSearchFields input[type="checkbox"]');

						fields.on('change', function(e){
							e.preventDefault();
							$filter.find('input[name="f_search_autocomplete"]').closest('tr').css('display', (fields.filter(':not([name="f_search_by_title"]):checked').length ? 'none' : 'table-row'));
						});

						if(typeof searchBy != 'undefined' && searchBy != '') {
							if(searchBy == 'title' || searchBy == 'toc' || searchBy == 'tac') {
								fields.filter('[name="f_search_by_title"]').prop('checked', true);
							}
							if(searchBy == 'content' || searchBy == 'coe' || searchBy == 'toc' || searchBy == 'tac') {
								fields.filter('[name="f_search_by_content"]').prop('checked', true);
							}
							if(searchBy == 'excerpt' || searchBy == 'coe') {
								fields.filter('[name="f_search_by_excerpt"]').prop('checked', true);
							}
							if(searchBy == 'tac') {
								$filter.find('select[name="f_query_logic"]').val('and');
							}
							$filter.find('input[name="f_search_by"]').val('');
						}
						fields.filter('[name="f_search_by_title"]').trigger('change');
						break;

					case 'wpfRating':
						_this.initColorPicker($filter.find('.wpfStarsTypeBlock .woobewoo-color-result'));
						break;
				}
				// Frontend Type: Buttons
				_this.initButtonsFilter($filter, settings);
				// Frontend Type: Switch
				_this.initColorPicker($filter.find('.wpfSwitchTypeBlock .woobewoo-color-result'));

				$filter.find('select[name="f_mlist[]"]').on('change', function() {
	    			_this.hideTermsOptions(jQuery(this));
		  		});

			});

			WpfAdminPage.constructor.prototype.hideTermsOptions = (function ($list) {
				var $termsContainers = $list.closest('.wpfFilter').find('ul.wpfTermsOptions');
				if($termsContainers.length == 0) return;

				var terms = $list.val();
				$termsContainers.each(function(){
					var lis = jQuery(this).find('li').removeClass('wpfHidden');
					if(terms != null && terms.length) {
						lis.each(function() {
							var li = jQuery(this);
							if(terms.indexOf(li.attr('data-term')) == -1) li.addClass('wpfHidden');
						});
					}
				});
			});

			WpfAdminPage.constructor.prototype.chooseIconPopup = (function () {
				var color = jQuery('input[name="settings[filter_loader_icon_color]"]').val();
				jQuery('body').on('click', '#chooseIconPopup .item-inner', function (e) {
					e.preventDefault();
					var el = jQuery(this),
						name = el.find('.preicon_img').attr('data-name'),
						countDiv = el.find('.preicon_img').attr('data-items');

					jQuery('input[name="settings[filter_loader_icon_name]"]').val(name);
					jQuery('input[name="settings[filter_loader_icon_number]"]').val(countDiv);
					if (name === 'spinner' || name === 'default') {
						jQuery('.wpfIconPreview').html('');
						jQuery('.wpfIconPreview').html('<div class="woobewoo-filter-loader spinner"></div>');
					} else {
						jQuery('.wpfIconPreview').html('');
						var htmlIcon = ' <div class="woobewoo-filter-loader la-' + name + ' la-2x" style="color: ' + color + ';">';
							//to display active elements for loader icon we need add div tags
							for (var i = 0; i < countDiv; i++) {
								htmlIcon += '<div></div>';
							}
						htmlIcon += '</div>';
						jQuery('.wpfIconPreview').html(htmlIcon);
					}
					$container.empty();
					$container.dialog('close');
				});
				var $container = jQuery('<div id="chooseIconPopup" style="display: none;" title="" /></div>').dialog({
					modal: true,
					autoOpen: false,
					width: 900,
					height: 750,
					buttons: {
						OK: function () {
							$container.empty();
							$container.dialog('close');
						},
						Cancel: function () {
							$container.empty();
							$container.dialog('close');
						}
					},
					create:function () {
						$(this).closest('.ui-dialog').addClass('woobewoo-plugin');
					}
				});

				var contentHtml = jQuery('.wpfLoaderIconTemplate').clone().removeClass('wpfHidden');
				contentHtml.find('div.preicon_img[data-name="default"] div').css({'backgroundColor': color});
				contentHtml.find('div.preicon_img').not('[data-name="default"]').css({'color':color});
				$container.append(contentHtml);

				var title = jQuery('.chooseLoaderIcon').text();
				$container.dialog("option", "title", title);
				$container.dialog('open');
				return false;
			});

			WpfAdminPage.constructor.prototype.changeButtonTermsPro = (function(filter, settings) {
				var _this = this.$obj,
					buttonsSettings = filter.find('.wpfButtonsTypeBlock'),
					optionForm = buttonsSettings.find('.wpfTermsOptionsForm').css('display', 'none').appendTo(buttonsSettings.find('.wpfSettingsPerTerm')),
					optionsContainer = buttonsSettings.find('ul.wpfTermsOptions').html(''),
					normalText = optionsContainer.attr('data-normal-text'),
					checkedText = optionsContainer.attr('data-checked-text');
				if(typeof settings == 'undefined') settings = [];

				filter.find('select[name="f_mlist[]"] option').each(function () {
					var term = jQuery(this),
						value = term.attr('value'),
						termName = term.text(),
						normalName = 'f_buttons_term'+value,
						checkedName = 'f_buttons_check_term'+value,						
						textName = 'f_buttons_text_term'+value,
						normalColor = (settings[normalName] ? settings[normalName] : ''),
						checkedColor = (settings[checkedName] ? settings[checkedName] : ''),
						lbText = (settings[textName] ? settings[textName] : ''),
						li = jQuery('<li class="settings-block-values" data-term="'+value+'"></li>');
					li.append('<div class="settings-value"><label>'+normalText+'</label><div class="wpfColorTermPreview" data-field="color_bg" style="background-color:'+normalColor+';"></div></div>');
					li.append('<div class="settings-value"><label>'+checkedText+'</label><div class="wpfColorTermPreview" data-color="checked" data-field="color_bg_check" style="background-color:'+checkedColor+';"></div></div>');
					li.append('<label class="settings-value wpfLabelTermPreview">'+(lbText == '' ? termName : lbText)+'</label>');
					li.append('<input type="hidden" name="'+normalName+'" data-field="color_bg" value="'+normalColor+'">');
					li.append('<input type="hidden" name="'+checkedName+'" data-field="color_bg_check" value="'+checkedColor+'">');
					li.append('<input type="hidden" name="'+textName+'" data-field="text_label" data-placeholder="'+termName+'" value="'+lbText+'">');
					li.append('<div class="clear"></div>');

					optionsContainer.append(li);
				});
				optionsContainer.find('li .wpfColorTermPreview').on('click', function() {
					_this.toggleTermOptions(optionForm, jQuery(this).closest('li'));
				});

				_this.hideTermsOptions(filter.find('select[name="f_mlist[]"]'));
			});

			WpfAdminPage.constructor.prototype.initButtonsFilter = (function(filter, settings) {
				var _this = this.$obj,
					buttonsSettings = filter.find('.wpfButtonsTypeBlock');
				if(buttonsSettings.length == 0) return;

				buttonsSettings.find('input[name="f_buttons_per_button"]').on('change', function() {
					if(jQuery(this).is(':checked')) buttonsSettings.find('.wpfSettingsPerTerm').removeClass('wpfHidden');
					else buttonsSettings.find('.wpfSettingsPerTerm').addClass('wpfHidden');					
				}).trigger('change');

				if(filter.attr('data-filter') != 'wpfAttribute') _this.changeButtonTermsPro(filter, settings);

				buttonsSettings.find('.wpfTermsOptionsForm .wpfTermsColorBg .woobewoo-color-result').wpColorPicker({
					hide: true,
					defaultColor: false,
					width: 200,
					border: false,
					change: function(event, ui) {
						var color = ui.color.toString(),
							wrapper = jQuery(event.target).closest('.woobewoo-color-picker'),
							result = wrapper.find('.woobewoo-color-result-text'),
							field = wrapper.closest('.wpfTermsColorBg').attr('data-field-temp'),
							li = wrapper.closest('li'),
							input = li.find('input[data-field="'+field+'"]');

						result.val(color).trigger('color-change');
						wrapper.find('.button').css('color', color);
						li.find('.wpfColorTermPreview[data-field="'+field+'"]').css('background-color', color);
						if(input.val() != color) input.val(color).trigger('wpf-update');
					},
					clear: function(event, ui) {
						var color = '',
							wrapper = jQuery(event.target).closest('.woobewoo-color-picker'),
							field = wrapper.closest('.wpfTermsColorBg').attr('data-field-temp'),
							li = wrapper.closest('li'),
							input = li.find('input[data-field="'+field+'"]');
						li.find('.wpfColorTermPreview[data-field="'+field+'"]').css('background-color', color);
						if(input.val() != color) input.val(color).trigger('wpf-update');
					}
				});

				buttonsSettings.find('.wpfTermsOptionsForm .wpfTermsTextLabel input').on('change', function(){
					var $this = jQuery(this),
						value = $this.val(),
						li = $this.closest('li');
					li.find('input[data-field="text_label"]').val(value).trigger('wpf-update');
					li.find('label.wpfLabelTermPreview').text(value == '' ? $this.attr('data-placeholder') : value);
				});

				WpfAdminPage.initColorPicker(buttonsSettings.find('.woobewoo-color-picker>.woobewoo-color-result'));
				
				return;
			});

			WpfAdminPage.constructor.prototype.initAttributeColorFilter = (function(filter, settings) {
				var _this = this.$obj,
					colorsSettings = filter.find('.wpfColorsTypeBlock');


				colorsSettings.find('input[name="f_colors_border"]').on('change', function(e){
					e.preventDefault();
					if($(this).prop('checked')) {
						colorsSettings.find('input[name^="f_colors_border_"]').trigger('change').closest('tr').css('display', 'table-row');
					} else {
						colorsSettings.find('input[name^="f_colors_border_"]').closest('tr').hide();
					}
				});//.trigger('change');
				colorsSettings.find('input[name="f_colors_size"]').on('change', function(e){
					e.preventDefault();
					var size = $(this).val();
					colorsSettings.find('.wpfColorTermPreview').css({'width': size + 'px', 'height': size + 'px'});
				}).trigger('change');			

				colorsSettings.find('.wpfTermsOptionsForm .wpfTermsColorBg .woobewoo-color-result').wpColorPicker({
					hide: true,
					defaultColor: false,
					width: 200,
					border: false,
					change: function(event, ui) {
						var color = ui.color.toString(),
							wrapper = jQuery(event.target).closest('.woobewoo-color-picker'),
							result = wrapper.find('.woobewoo-color-result-text'),
							li = wrapper.closest('li'),
							input = li.find('input[data-field="color_bg"]');

						result.val(color).trigger('color-change');
						wrapper.find('.button').css('color', color);
						li.find('.wpfColorTermPreview').css('background-color', color);
						if(input.val() != color) input.val(color).trigger('wpf-update');
					},
					clear: function(event, ui) {
						var li = jQuery(event.target).closest('li'),
							color = '',
							input = li.find('input[data-field="color_bg"]');
						li.find('.wpfColorTermPreview').css('background-color', color);
						if(input.val() != color) input.val(color).trigger('wpf-update');
					}
				});

				colorsSettings.find('.wpfTermsOptionsForm .wpfTermsColorLabel .woobewoo-color-result').wpColorPicker({
					hide: true,
					defaultColor: false,
					width: 200,
					border: false,
					change: function(event, ui) {
						var color = ui.color.toString(),
							wrapper = jQuery(event.target).closest('.woobewoo-color-picker'),
							result = wrapper.find('.woobewoo-color-result-text'),
							li = wrapper.closest('li'),
							input = li.find('input[data-field="color_label"]');

						result.val(color).trigger('color-change');
						wrapper.find('.button').css('color', color);
						li.find('label').css('color', color);
						if(input.val() != color) input.val(color).trigger('wpf-update');
					},
					clear: function(event, ui) {
						var li = jQuery(event.target).closest('li'),
							color = '',
							input = li.find('input[data-field="color_label"]');
						li.find('label').removeAttr('style');
						if(input.val() != color) input.val(color).trigger('wpf-update');
					}
				});

				colorsSettings.find('.wpfTermsOptionsForm .wpfTermsTextLabel input').on('change', function(){
					var $this = jQuery(this),
						value = $this.val(),
						li = $this.closest('li');
					li.find('input[data-field="text_label"]').val(value).trigger('wpf-update');
					li.find('label.wpfLabelTermPreview').text(value == '' ? $this.attr('data-placeholder') : value);
				});
				_this.initIconSelector(colorsSettings.find('.wpfTermsSelectIcon'));

				colorsSettings.find('input[name="f_colors_hor_spacing"]').on('change', function(e){
					e.preventDefault();
					colorsSettings.find('.wpfColorsFilterHor label[data-term]').css('margin-right', jQuery(this).val()+'px');
				});

				WpfAdminPage.initColorPicker(colorsSettings.find('.woobewoo-color-picker>.woobewoo-color-result'));
				return;
			});
			
			WpfAdminPage.constructor.prototype.initSliderFilter = (function(filter, settings) {
				var _this = this.$obj,
					$filter = filter;
				
				var skinSettinges = $filter.find('div.wpfSkinsBlock'),
					skinColor = $filter.find('input[name="f_skin_color"]'),
					gridCheckbox = $filter.find('input[name="f_skin_grid"]'),
					labelsMinMax = $filter.find('input[name="f_skin_labels_minmax"]'),
					labelsFromTo = $filter.find('input[name="f_skin_labels_fromto"]');
				
				$filter.find('select[name="f_skin_type"]').on('change', function(e){
					e.preventDefault();
					var skin = jQuery(this).val();
					if(skin == 'default') {
						skinSettinges.addClass('wpfHidden');
					} else {
						jQuery('#wpfPriceStyle').html('');
						jQuery('input[name="f_skin_css"]').val('');
						_this.setSkinColor(skin, skinColor.val(), labelsMinMax.is(':checked') || labelsFromTo.is(':checked'));
						skinSettinges.removeClass('wpfHidden');
					}
				}).trigger('change');
				
				$filter.find('input[name="f_skin_labels_fromto"], input[name="f_skin_labels_minmax"]').on('change', function(e){
					e.preventDefault();
					_this.setSkinColor($filter.find('select[name="f_skin_type"]').val(), skinColor.val(), labelsMinMax.is(':checked') || labelsFromTo.is(':checked'));
				});
				
				skinSettinges.find('.woobewoo-color-result').wpColorPicker({
					hide: true,
					defaultColor: false,
					width: 200,
					border: false,
					change: function(event, ui) {
						var color = ui.color.toString(),
							wrapper = jQuery(event.target).closest('.woobewoo-color-picker'),
							result = wrapper.find('.woobewoo-color-result-text');
						
						result.val(color).trigger('color-change');
						wrapper.find('.button').css('color', color);
						_this.setSkinColor($filter.find('select[name="f_skin_type"]').val(), ui.color.toString(), labelsMinMax.is(':checked') || labelsFromTo.is(':checked'));
					}
				});
				
				return;
			});

			WpfAdminPage.constructor.prototype.initIconSelector = (function ($wrapper) {
				$wrapper.find('a').on('click', function(e){
					e.preventDefault();
					var $button = jQuery(this),
						$li = $button.closest('li'),
						$input = $li.find('input[data-field="icon_bg"]'),
						$preview = $li.find('.wpfColorTermPreview'),
						_custom_media = true;
					wp.media.editor.send.attachment = function(props, attachment){
						wp.media.editor._attachSent = true;
						if(_custom_media) {
							var selectedUrl = attachment.url,
								imgWidth = attachment.width,
								imgHeight = attachment.height;
							if(props && props.size && attachment.sizes && attachment.sizes[props.size] && attachment.sizes[props.size].url) {
								var imgSize = attachment.sizes[props.size];
								selectedUrl = imgSize.url;
								imgWidth = imgSize.width;
								imgHeight = imgSize.height;
							}
							$input.val('background-image:url('+selectedUrl+');width:'+imgWidth+'px!important;height:'+imgHeight+'px!important;').trigger('wpf-update');
							$preview.css({'background-image': 'url('+selectedUrl+')', 'width': imgWidth+'px', 'height': imgHeight+'px' });
						} else {
							return _orig_send_attachment.apply( this, [props, attachment] );
						}
					};
					wp.media.editor.insert = function(html) {
						if(_custom_media) {
							if(wp.media.editor._attachSent) {
								wp.media.editor._attachSent = false;
								return;
							}
							if(html && html != "") {
								var selectedUrl = $(html).attr('src');
								if(selectedUrl) {
									$input.val('background-image:url('+selectedUrl+');').trigger('wpf-update');
									$preview.css('background-image', 'url('+selectedUrl+')');
								}
							}
						}
					};
					wp.media.editor.open($button);
					return false;
				});
				$wrapper.find('.wpfTermsRemoveIcon').on('click', function(e) {
					var $li = jQuery(this).closest('li');
					$li.find('input[data-field="icon_bg"]').val('').trigger('wpf-update');
					$li.find('.wpfColorTermPreview').css({'background-image': '', 'width': '', 'height': '' });
				});
			});

			WpfAdminPage.constructor.prototype.changeAttributeTermsPro = (function (filter, settings) {
				var _this = this.$obj,
					colorsSettings = filter.find('.wpfColorsTypeBlock'),
					optionForm = filter.find('.wpfColorsTypeBlock .wpfTermsOptionsForm').css('display', 'none').appendTo(colorsSettings.find('.wpfColorsTypeOptions')),
					iconColorsContainer = colorsSettings.find('.wpfAttributesColors ul').html(''),
					attrSlug = filter.find('select[name="f_list"]').val();
				if (attrSlug == '0') return;

				if(typeof settings == 'undefined') {
					var filterId = filter.attr('id');
					if(filterId) {
						var filterNum = filterId.replace('wpfFilter', '');
						settings = (_this.filtersSettings && filterNum in _this.filtersSettings ? _this.filtersSettings[filterNum]['settings'] : []);
					} else settings = [];
				}
				var options = jQuery('.wpfAttributesTerms input[name="attr-'+attrSlug+'"]'),
					attrTypes = jQuery('.wpfAttributesTerms input[name="attr_types"]');
				if(typeof(options) == 'undefined' || options.length == 0) return;

				try {
					var terms = JSON.parse(options.val()),
						keys = JSON.parse(options.attr('data-order')),
						types = JSON.parse(attrTypes.val());
				}catch(e){
					var terms = [],
						keys = [],
						types = [];
				}
				var attrType = attrSlug in types ? types[attrSlug] : '',
					frontendType = filter.find('select[name="f_frontend_type"]');

				keys.forEach(function (value) {
					if(value in terms) {
						var bgColorName = 'f_colors_term'+value,
							iconName = 'f_colors_icon_term'+value,						
							lbColorName = 'f_colors_label_term'+value,
							lbTextName = 'f_colors_text_term'+value,
							termName = terms[value],
							bgColor = (settings[bgColorName] ? settings[bgColorName] : (attrType == 'color_picker' ? value : '')),
							iconStyle = (settings[iconName] ? settings[iconName] : ''),
							lbColor = (settings[lbColorName] ? settings[lbColorName] : ''),
							lbText = (settings[lbTextName] ? settings[lbTextName] : ''),
							li = jQuery('<li data-term="'+value+'"><div class="wpfColorTermPreview" style="background-color:'+bgColor+';'+(iconStyle == '' ? '' : iconStyle) + '"></div></li>');
							li.append('<label class="wpfLabelTermPreview"'+(lbColorName.length ? ' style="color:'+lbColor+';"' : '')+'>'+(lbText == '' ? termName : lbText)+'</label>');
							li.append('<input type="hidden" name="'+bgColorName+'" data-field="color_bg" value="'+bgColor+'">');
							li.append('<input type="hidden" name="'+iconName+'" data-field="icon_bg" value="'+iconStyle+'">');
							li.append('<input type="hidden" name="'+lbColorName+'" data-field="color_label" value="'+lbColor+'">');
							li.append('<input type="hidden" name="'+lbTextName+'" data-field="text_label" data-placeholder="'+termName+'" value="'+lbText+'">');
						iconColorsContainer.append(li);
					}
				});
				iconColorsContainer.find('li .wpfColorTermPreview').on('click', function() {
					_this.toggleTermOptions(optionForm, jQuery(this).parent());
				});
				_this.hideTermsOptions(filter.find('select[name="f_mlist[]"]'));

				frontendType.find('option').show();
				switch(attrType) {
					case 'color_picker': 
						frontendType.find('option:not([value="colors"])').hide();
						frontendType.val('colors').trigger('change');
						break;
					case 'true_false':
						frontendType.find('option:not([value="switch"],[value="list"])').hide();
						frontendType.val('switch').trigger('change');
						break;
					default:
						break;
				}
				_this.changeButtonTermsPro(filter, settings);
			});

			WpfAdminPage.constructor.prototype.toggleTermOptions = (function(optionForm, elem) {
				var _this = this.$obj;
				if(optionForm.css('display') == 'none') {
					_this.showTermOptions(optionForm, elem);
				} else {
					optionForm.slideToggle(400, function() {
						if(optionForm.parent().attr('data-term') != elem.attr('data-term')) {
							_this.showTermOptions(optionForm, elem);
						}
					});
				}
			});
			WpfAdminPage.constructor.prototype.showTermOptions = (function(optionForm, elem) {
				optionForm.appendTo(elem);
				elem.find('input[data-field]').each(function() {
					var $this = jQuery(this),
						value = $this.val(),
						tempField = optionForm.find('div[data-field-temp="'+$this.attr('data-field')+'"]');
					if(tempField.length) {
						var fieldType = tempField.attr('data-field-type');
						switch (fieldType) {
							case 'color-picker':
								//tempField.find('.woobewoo-color-result-text').val(value).trigger('change');
								tempField.find('.woobewoo-color-result-text').val('');
								if(value == '') tempField.find('.wp-picker-clear').trigger('click');
								else tempField.find('.woobewoo-color-result').wpColorPicker('color', value);
								break;
							case 'text':
								var placeholder = $this.attr('data-placeholder');
								tempField.find('input').attr('placeholder', placeholder).val(value);
								break;
						}
					}
				});
				optionForm.slideToggle(400);
			});

	        WpfAdminPage.constructor.prototype.initModalIcons = (function(itemVal, item) {
	            var _this = this.$obj,
	            	options = {
	                	modal: true,
	                	autoOpen: false,
	                	width: 800,
	                	height: 500,
	                	buttons: {
	                    	OK: function () {
	                        	$container.dialog('close');
	                    	},
	                    	Cancel: function () {
	                        	$container.dialog('close');
		                    }
		                }
	    	        };
	            var $container = jQuery('<div id="wpfSetupImageIcons"></div>').dialog( options ),
	            	fontAwesome = jQuery('<div class="wpfImageIconsFontAwesome"></div>');
	            fontAwesome.append('<table><tbody></tbody></table>');
	            if (typeof FONT_AWESOME_DATA !== 'undefined') {
	            	var tr = jQuery('<tr/>');
	                FONT_AWESOME_DATA.forEach(function(data,index){
	                	var td = jQuery('<td/>').html('<i class="fa '+ data+ '"></i> '+ data);
	                    td.attr('data-value', data);
	                    tr.append(td);
	                	if ((index + 1) % 4 == 0) {
	                        fontAwesome.find('tbody').append(tr);
	                        tr = jQuery('<tr/>');
						}
					});
				}
	            $container.append(fontAwesome);
	            if (typeof itemVal !== 'undefined') {
	                fontAwesome.find('td[data-value="'+ itemVal+ '"]').addClass('active');
				}
	            fontAwesome.find('td').on('click',function(e){
	            	jQuery(this).closest('table').find('td').removeClass('active');
	                jQuery(this).addClass('active');
				});
	        });
	        WpfAdminPage.initModalIcons();

	        WpfAdminPage.constructor.prototype.loadModalIcons = (function(itemVal, item){
	            var _this = this.$obj,
	            	$container = jQuery('#wpfSetupImageIcons');

	            $container.dialog('open');
	            if (typeof itemVal !== 'undefined') {
	                $container.find('td[data-value="'+ itemVal+ '"]').addClass('active');
	            }
	            $container.dialog({
	                beforeClose: function( event, ui ) {
	                    var value = $container.find('td.active').attr('data-value');
	                    if (typeof item !== 'undefined') {
	                        item.attr('data-value', value);
	                        item.find('i').attr('class', 'fa ' + value);
	                        item.siblings('input').val(value);
	                    }
	                    $container.find('td').removeClass('active');
					}
	            });
	        	return false;
			});
		}
	}
}(window.jQuery));
