/**
 * Theme Customizer enhancements for a better user experience.
 * Contains handlers to make Theme Customizer preview reload changes asynchronously.
 */

( function( $ ) {

	// Basic Checks
	if( 'undefined' == typeof hootInlineStyles || ! $.isArray( hootInlineStyles ) )
		window.hootInlineStyles = [ '', '', {}, {} ];
	if ( !hootInlineStyles[0] || typeof hootInlineStyles[0] !== 'string' ) hootInlineStyles[0] = '';
	hootInlineStyles[1] = hootInlineStyles[1] ? true : false;
	if ( !hootInlineStyles[2] || typeof hootInlineStyles[2] !== 'object' ) hootInlineStyles[2] = {};
	if ( !hootInlineStyles[3] || typeof hootInlineStyles[3] !== 'object' ) hootInlineStyles[3] = {};

	// Make sure we have a hook
	var $csshandle_hook = hootInlineStyles[0] ? $( '#' + hootInlineStyles[0] + '-inline-css' ) : [];
	if ( ! $csshandle_hook.length ) {
		$csshandle_hook = $('<style id="hoot-customize-hookpreview" type="text/css"></style>').appendTo('head');
	}

	// Variables
	var hootpload = hootInlineStyles[1],
		settingMap = hootInlineStyles[2],
		defaultMap = hootInlineStyles[3];
	settingMap = typeof settingMap === 'object' ? settingMap : {};
	defaultMap = typeof defaultMap === 'object' ? defaultMap : {};

	/*** Utility ***/
	function hootAddStyleTag( setting ) {
		if ( $( 'hoot-customize-' + setting ).length === 0 ) {
			$csshandle_hook.after( '<style id="hoot-customize-' + setting + '" type="text/css"></style>' );
		}
	}
	function hootUpdateCss( setting, value, defaultSuffix='' ) {
		var $target = $( '#hoot-customize-' + setting ),
			mapCssVar = settingMap[setting],
			mapDefault = defaultMap[setting],
			needsRefresh = false;
		if ( ! $target.length || ! mapCssVar ) {
			needsRefresh = true;
		} else {
			if ( typeof value !== 'object' ) {
				if ( value || value === 0 || value === '0' ) {
					$target.html( ':root{' + mapCssVar + ':' + value +'}' );
				} else if ( mapDefault || mapDefault === 0 || mapDefault === '0' ) {
					$target.html( ':root{' + mapCssVar + ':' + mapDefault + defaultSuffix +'}' );
				} else {
					needsRefresh = true;
				}
			}
			else if ( typeof value.media === 'object' ) {
				mapDefault = typeof mapDefault === 'object' ? mapDefault : {};
				var cssString = '';
				if ( typeof value.media.desktop === 'string' || typeof value.media.desktop === 'number' ) {
					cssString += ':root{' + mapCssVar + ':' + value.media.desktop +'}';
				} else if ( mapDefault.desktop || mapDefault.desktop===0 || mapDefault.desktop==='0' ) {
					cssString += ':root{' + mapCssVar + ':' + mapDefault.desktop + defaultSuffix +'}';
				} else {
					needsRefresh = true;
				}
				if ( typeof value.media.tablet === 'string' || typeof value.media.tablet === 'number' ) {
					cssString += '@media only screen and (max-width: 969px){:root{' + mapCssVar + ':' + value.media.tablet +'}}';
				} else if ( mapDefault.tablet || mapDefault.tablet===0 || mapDefault.tablet==='0' ) {
					cssString += '@media only screen and (max-width: 969px){:root{' + mapCssVar + ':' + mapDefault.tablet + defaultSuffix +'}}';
				} else {
					needsRefresh = true;
				}
				if ( typeof value.media.mobile === 'string' || typeof value.media.mobile === 'number' ) {
					cssString += '@media only screen and (max-width: 600px){:root{' + mapCssVar + ':' + value.media.mobile +'}}';
				} else if ( mapDefault.mobile || mapDefault.mobile===0 || mapDefault.mobile==='0' ) {
					cssString += '@media only screen and (max-width: 600px){:root{' + mapCssVar + ':' + mapDefault.mobile + defaultSuffix +'}}';
				} else {
					needsRefresh = true;
				}
				if ( cssString ) {
					$target.html( cssString );
				}
			}
			else {
				var cssString = '';
				for ( var varid in value ) { if ( value.hasOwnProperty(varid) ) {
					var ivar = mapCssVar.replace( 'varid', varid );
					var ival = value[varid];
					if ( ival || ival === 0 || ival === '0' ) {
						cssString += ivar + ':' + ival + ';';
					} else {
						needsRefresh = true;
					}
				} }
				if ( cssString ) {
					$target.html( ':root{' + cssString + '}' );
				}
			}
		}
		if ( needsRefresh ) {
			wp.customize.preview.send( 'refresh' );
		}
	}
	// @credit: https://css-tricks.com/snippets/javascript/lighten-darken-color/
	function hootcolor(col, amt) {
		var usePound = false;
		if (col[0] == "#") { col = col.slice(1); usePound = true; }
		var num = parseInt(col,16);
		var r = (num >> 16) + amt; if (r > 255) r = 255; else if  (r < 0) r = 0;
		var b = ((num >> 8) & 0x00FF) + amt; if (b > 255) b = 255; else if  (b < 0) b = 0;
		var g = (num & 0x0000FF) + amt; if (g > 255) g = 255; else if (g < 0) g = 0;
		return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
	}
	function getHexAlpha(val) {
		// strip the #
		var hex = val.charAt(0) === '#' ? val.slice(1) : val;
		var len = hex.length;
		// check if it’s a hex color (we dont support rgb/rgba)
		if (!/^#([0-9a-f]{3,8})$/i.test(val)) return 1;
		// if 3, 4, or 6 chars -> no alpha
		if (len === 3 || len === 4 || len === 6) return 1;
		// if 8 chars -> last 2 are alpha
		if (len === 8) {
			var a = hex.slice(6); // last 2
			// convert from 00–FF to 0–1
			return Math.round((parseInt(a, 16) / 255) * 1000) / 1000; // rounded to 3 decimals
		}
		// default
		return 1;
	}
	function hootResolveRange( newval, suffix='', allowZero=true, allowNegative=false ) {
		try {
			var newvalObj = typeof newval === 'string' ? JSON.parse( newval ) : newval,
				// default fallback (if not explicitly set to 'on') is always 'off' i.e. seperate medias
				allDevices = ! newvalObj.alldevices || newvalObj.alldevices !== 'on' ? 'off' : 'on';
			if ( newvalObj.desktop || newvalObj.tablet || newvalObj.mobile ) {
				var mediaVal = { media: {} }
				for ( var device in newvalObj ) { if ( newvalObj.hasOwnProperty(device) ) {
					if ( device === 'desktop' || device === 'tablet' || device === 'mobile' ) { // no need to add alldevices to mediaVal as we are creating this for hootUpdateCss
						var usedevicevals = allDevices==='on' ? 'desktop' : device;
						var deviceval = parseInt( newvalObj[usedevicevals] );
						if ( !isNaN(deviceval) ) {
							deviceval = ( !allowNegative && deviceval < 0 ) || ( !allowZero && deviceval === 0 ) ? false : deviceval;
							deviceval = deviceval || deviceval === 0 ? deviceval + suffix : false;
						} else { // this should not happen as range should always give a number
							deviceval = false;
						}
						mediaVal.media[device] = deviceval ? deviceval : false;
					}
				} }
				return mediaVal;
			} else {
				// This function does not handle non mediaquery values
				return newval;
			}
		} catch (error) {
			console.error("Invalid JSON string:", error.message);
		}
	}
	function hootResolveSpacers( newval, allowNegative=false ) {
		try {
			var newvalObj = JSON.parse( newval ),
				// default fallback (if not explicitly set to 'on') is always 'off' i.e. seperate medias
				allDevices = ! newvalObj.alldevices || newvalObj.alldevices !== 'on' ? 'off' : 'on';
			if ( newvalObj.desktop || newvalObj.tablet || newvalObj.mobile ) {
				var mediaVal = { media: {} }
				for ( var device in newvalObj ) { if ( newvalObj.hasOwnProperty(device) ) {
					if ( device === 'desktop' || device === 'tablet' || device === 'mobile' ) { // no need to add alldevices to mediaVal as we are creating this for hootUpdateCss
						var usedevicevals = allDevices==='on' ? 'desktop' : device;
						var deviceval = '';
						var spacekeys = ['t','r','b','l'];
						for ( var i = 0; i < spacekeys.length; i++ ) {
							var key = spacekeys[i];
							var newvalint = parseInt( newvalObj[usedevicevals][key] );
							if ( !isNaN(newvalint) && (allowNegative || newvalint >= 0) ) { //don't allow negative
								deviceval += newvalint + 'px ';
							} else {
								deviceval += '0px ';
							}
						}
						mediaVal.media[device] = deviceval;
					}
				} }
				return mediaVal;
			} else {
						var deviceval = '';
						var spacekeys = ['t','r','b','l'];
						for ( var i = 0; i < spacekeys.length; i++ ) {
							var key = spacekeys[i];
							var newvalint = parseInt( newvalObj[key] );
							if ( !isNaN(newvalint) && (allowNegative || newvalint >= 0) ) { //don't allow negative
								deviceval += newvalint + 'px ';
							} else {
								deviceval += '0px ';
							}
						}
				return deviceval;
			}
		} catch (error) {
			console.error("Invalid JSON string:", error.message);
		}
	}
	function hootResolveFpCols( columns ) {
		colArr = [];
		switch ( columns ) {
			case '100'         : colArr = [12];      break;
			case '50-50'       : colArr = [6,6];     break;
			case '33-66'       : colArr = [4,8];     break;
			case '66-33'       : colArr = [8,4];     break;
			case '25-75'       : colArr = [3,9];     break;
			case '75-25'       : colArr = [9,3];     break;
			case '33-33-33'    : colArr = [4,4,4];   break;
			case '25-25-50'    : colArr = [3,3,6];   break;
			case '25-50-25'    : colArr = [3,6,3];   break;
			case '50-25-25'    : colArr = [6,3,3];   break;
			case '25-25-25-25' : colArr = [3,3,3,3]; break;
			default            : colArr = [12];      break; // default: 100 if undefined
		}
		return colArr;
	}
	function hootUpdateBgPatt( cssTagId=false, patt=false ) {
		if ( cssTagId ) {
			patt = patt.replace(/\/\/theme\/\/|\/\/plugin\/\/|\/\/png|\/\/jpg/g, function(m) {
				return { '//theme//': settingMap.themeimgdir, '//plugin//': settingMap.pluginimgdir, '//png': '.png', '//jpg': '.jpg' }[m];
			});
			hootUpdateCss( cssTagId, {
				bgimg: patt && patt !== 0 && patt !== '0' ? 'url(' + patt + ')' : 'none',
				bgrepeat: 'repeat',
				bgpos: '0 0',
				bgatch: 'scroll',
				bgsize: 'auto',
			} );
		}
	}
	function hootUpdateBgImg( cssTagId=false, settingId=false, prop=false, val=0 ) {
		if ( cssTagId && settingId && prop ) {
			var bgimg, bgrepeat, bgpos, bgatch, bgsize;
			var newvalArray = {
				bgimg: 'none',
				bgrepeat: 'repeat',
				bgpos: '0 0',
				bgatch: 'scroll',
				bgsize: 'auto',
			};

			if ( prop === 'bgimg' ) { bgimg = val; }
			else { wp.customize( settingId + '-image', function( setting ) { bgimg = setting.get(); }); }
			if ( bgimg ) newvalArray.bgimg = 'url(' + bgimg + ')';

			// Get other values: needed only if bgimg is set, else let them be default as it doesn't matter
			if ( bgimg && bgimg !== 0 && bgimg !== '0' ) {

				if ( prop === 'bgrepeat' ) { bgrepeat = val; }
				else { wp.customize( settingId + '-repeat', function( setting ) { bgrepeat = setting.get(); }); }
				if ( bgrepeat ) newvalArray.bgrepeat = bgrepeat;

				if ( prop === 'bgpos' ) { bgpos = val; }
				else { wp.customize( settingId + '-position', function( setting ) { bgpos = setting.get(); }); }
				if ( bgpos ) newvalArray.bgpos = bgpos;

				if ( prop === 'bgatch' ) { bgatch = val; }
				else { wp.customize( settingId + '-attachment', function( setting ) { bgatch = setting.get(); }); }
				if ( bgatch ) newvalArray.bgatch = bgatch;

				if ( prop === 'bgsize' ) { bgsize = val; }
				else { wp.customize( settingId + '-size', function( setting ) { bgsize = setting.get(); }); }
				if ( bgsize ) newvalArray.bgsize = bgsize;

			}
			hootUpdateCss( cssTagId, newvalArray );
		}
	}
	// Moved to singular approach of using [JSON.stringify( $optionsform.serializeArray() ) + PHP json_decode()]
	function hootDeserialize( serializedStr ) {
		try {
			var jsonObject = JSON.parse(serializedStr);
			if (typeof jsonObject === 'object' && jsonObject !== null) {
				return jsonObject;
			}
		} catch (e) {} // Not a JSON string, try with URLSearchParams
		return false;
	}
	function getMultilevelObjVal(obj, keys) {
		// If keys is a string, split it into an array
		if (typeof keys === 'string') {
			keys = keys.split('.');
		}
		return keys.reduce((acc, key) => {
			return acc && typeof acc === 'object' && acc !== null && acc[key] !== undefined
				? acc[key]
				: undefined;
		}, obj);
	}



	/*** Site title and description. ***/

	wp.customize( 'blogname', function( value ) {
		value.bind( function( newval ) {
			$( '#site-logo-text #site-title a, #site-logo-mixed #site-title a' ).html( newval );
		} );
	} );

	wp.customize( 'blogdescription', function( value ) {
		value.bind( function( newval ) {
			$( '#site-description' ).html( newval );
		} );
	} );

	/** Theme Settings **/

	wp.customize( 'site_layout', function( value ) {
		value.bind( function( newval ) {
			$( '#page-wrapper' ).removeClass('hgrid site-boxed site-stretch');
			if ( newval == 'boxed' )
				$( '#page-wrapper' ).addClass('hgrid site-boxed');
			else
				$( '#page-wrapper' ).addClass('site-stretch');
		} );
	} );

	function sidebar_width_px( setting, newval ) {
		var newvalint = parseInt(newval);
		newvalint = !isNaN(newvalint) && newvalint > 0 ? newvalint+'px' : false; // don't allow 0 or negative
		if ( !newvalint ) { // Redundancy Check as value should always exist in a range control
			newvalint = defaultMap.sidebar_width_px || '350';
			newvalint = newvalint+'px';
		}
		hootUpdateCss( setting, newvalint );
	}
	function sidebar_width_pcnt( setting, newval ) {
		var newvalint = parseInt(newval);
		newvalint = !isNaN(newvalint) && newvalint >= 0 && newvalint <= 100 ? newvalint+'%' : false; // don't allow 0 or negative
		if ( !newvalint ) { // Redundancy Check as value should always exist in a range control
			newvalint = defaultMap.sidebar_width_pcnt || '25';
			newvalint = newvalint+'%';
		}
		hootUpdateCss( setting, newvalint );
	}
	wp.customize( 'sidebar1_width', function( value ) {
		hootAddStyleTag( 'sidebar1_width' );
		value.bind( function( newval ) {
			if ( newval === 'auto' ) {
				var mapDefault = defaultMap.sidebar_width_pcnt || '25';
				hootUpdateCss( 'sidebar1_width', mapDefault+'%' );
			} else if ( newval === 'px' ) {
				var sbval = ''; wp.customize( 'sidebar1_width_px', function( setting ) { sbval = setting.get(); });
				sidebar_width_px( 'sidebar1_width', sbval );
			} else if ( newval === 'pcnt' ) {
				var sbval = ''; wp.customize( 'sidebar1_width_pcnt', function( setting ) { sbval = setting.get(); });
				sidebar_width_pcnt( 'sidebar1_width', sbval );
			}
		} );
	} );
	wp.customize( 'sidebar1_width_px', function( value ) {
		value.bind( function( newval ) {
			var sbtype = ''; wp.customize( 'sidebar1_width', function( setting ) { sbtype = setting.get(); });
			if ( sbtype == 'px' ) {
				sidebar_width_px( 'sidebar1_width', newval );
			}
		} );
	} );
	wp.customize( 'sidebar1_width_pcnt', function( value ) {
		value.bind( function( newval ) {
			var sbtype = ''; wp.customize( 'sidebar1_width', function( setting ) { sbtype = setting.get(); });
			if ( sbtype == 'pcnt' ) {
				sidebar_width_pcnt( 'sidebar1_width', newval );
			}
		} );
	} );
	wp.customize( 'sidebar2_width', function( value ) {
		hootAddStyleTag( 'sidebar2_width' );
		value.bind( function( newval ) {
			if ( newval === 'auto' ) {
				var mapDefault = defaultMap.sidebar_width_pcnt || '25';
				hootUpdateCss( 'sidebar2_width', mapDefault+'%' );
			} else if ( newval === 'px' ) {
				var sbval = ''; wp.customize( 'sidebar2_width_px', function( setting ) { sbval = setting.get(); });
				sidebar_width_px( 'sidebar2_width', sbval );
			} else if ( newval === 'pcnt' ) {
				var sbval = ''; wp.customize( 'sidebar2_width_pcnt', function( setting ) { sbval = setting.get(); });
				sidebar_width_pcnt( 'sidebar2_width', sbval );
			}
		} );
	} );
	wp.customize( 'sidebar2_width_px', function( value ) {
		value.bind( function( newval ) {
			var sbtype = ''; wp.customize( 'sidebar2_width', function( setting ) { sbtype = setting.get(); });
			if ( sbtype == 'px' ) {
				sidebar_width_px( 'sidebar2_width', newval );
			}
		} );
	} );
	wp.customize( 'sidebar2_width_pcnt', function( value ) {
		value.bind( function( newval ) {
			var sbtype = ''; wp.customize( 'sidebar2_width', function( setting ) { sbtype = setting.get(); });
			if ( sbtype == 'pcnt' ) {
				sidebar_width_pcnt( 'sidebar2_width', newval );
			}
		} );
	} );

	wp.customize( 'disable_goto_top', function( value ) {
		value.bind( function( newval ) {
			if (newval) $('.fixed-goto-top').addClass('hootnoshow');
			else        $('.fixed-goto-top').removeClass('hootnoshow');
		} );
	} );
	wp.customize( 'goto_top_mobile', function( value ) {
		value.bind( function( newval ) {
			if (newval) $('.fixed-goto-top').removeClass('hidemobile');
			else        $('.fixed-goto-top').addClass('hidemobile');
		} );
	} );
	wp.customize( 'goto_top_icon', function( value ) {
		value.bind( function( newval ) {
			if (newval) {
				$('.fixed-goto-top i').removeClass().addClass(newval);
			}
		} );
	} );
	wp.customize( 'goto_top_icon_style', function( value ) {
		value.bind( function( newval ) {
			if (newval) {
				$('.fixed-goto-top').removeClass('goto-top-style1 goto-top-style2 goto-top-style3 goto-top-style4 goto-top-style5 goto-top-style6 goto-top-style7 goto-top-style8').addClass('goto-top-'+newval);
			}
		} );
	} );

	$.each( [ 'goto_top_offset', 'widgetmargin', 'logo_image_width' ], function( index, setid ) {
		wp.customize( setid, function( value ) {
			hootAddStyleTag( setid );
			var allowZero = setid === 'logo_image_width' ? false : true,
				allowNegative = false;
			value.bind( function( newval ) {
				var newval = hootResolveRange(newval, 'px', allowZero, allowNegative);
				if ( ! newval ) { // This should not happen! // should be an object with media
					newval = { media:{desktop:false,tablet:false,mobile:false} };
				}
				hootUpdateCss( setid, newval, 'px' );
			} );
		} );
	} );

	wp.customize( 'topann_sticky', function( value ) {
		value.bind( function( newval ) {
			if (newval)
				$('#topann').addClass('topann-stick');
			else
				$('#topann').removeClass('topann-stick');
		} );
	} );
	wp.customize( 'topann_imageX', function( value ) {
		value.bind( function( newval ) {
			var imgasbg = 0;
			wp.customize( 'topann_imgasbg', function( setting ) { imgasbg = setting.get(); });
			if (newval) {
				$('#topann').removeClass('hootnoshow');
			} else {
				var title, content;
				wp.customize( 'topann_content_title', function( setting ) { title = setting.get(); });
				wp.customize( 'topann_content', function( setting ) { content = setting.get(); });
				if ( ! title && ! content ) { $('#topann').addClass('hootnoshow'); }
			}
			if (newval) {
				if ( imgasbg ) {
					$('#topann').css('background-image', 'url(' + newval + ')');
				} else {
					$('.topann-inlineimg img').removeClass('hootnoshow').attr('src', newval);
				}
			} else {
				if ( imgasbg ) {
					$('#topann').css('background-image', 'none');
				} else {
					$('.topann-inlineimg img').addClass('hootnoshow');
				}
			}
		} );
	} );
	wp.customize( 'topann_imgasbg', function( value ) {
		value.bind( function( newval ) {
			if ( ! $('#topann').hasClass( 'hootnoshow' ) ) {
				wp.customize.preview.send( 'refresh' );
				// Fallback to content's partial refresh to handle changes
				var partial = wp.customize.selectiveRefresh.partial('topann_content_partial');
				if ( partial ) { partial.refresh(); } else { wp.customize.preview.send( 'refresh' ); }
			}
		} );
	} );
	wp.customize( 'topann_imgstretch', function( value ) {
		value.bind( function( newval ) {
			if (newval) {
				$('#topann').addClass('topann-imgstretch');
			} else {
				$('#topann').removeClass('topann-imgstretch');
			}
		} );
	} );
	wp.customize( 'topann_content_stretch', function( value ) {
		value.bind( function( newval ) {
			if (newval === 'stretch') {
				$('#topann').removeClass('topann-grid').addClass('topann-stretch');
			} else {
				$('#topann').removeClass('topann-stretch').addClass('topann-grid');
			}
			var nopad = 0;
			wp.customize( 'topann_content_nopad', function( setting ) { nopad = setting.get(); });
			if (newval === 'stretch' && nopad) {
				$('#topann').addClass('topann-nopad');
			} else {
				$('#topann').removeClass('topann-nopad');
			}
		} );
	} );
	wp.customize( 'topann_content_nopad', function( value ) {
		value.bind( function( newval ) {
			var stretch;
			wp.customize( 'topann_content_stretch', function( setting ) { stretch = setting.get(); });
			if (newval && stretch === 'stretch') {
				$('#topann').addClass('topann-nopad');
			} else {
				$('#topann').removeClass('topann-nopad');
			}
		} );
	} );
	wp.customize( 'topann_content_style', function( value ) {
		value.bind( function( newval ) {
			if (typeof newval === 'string') {
				$('.topann-contentbox').removeClass('textstyle-dark textstyle-light textstyle-dark-on-light textstyle-light-on-dark textstyle-custom').addClass('textstyle-'+newval);
			}
		} );
	} );
	wp.customize( 'topann_content_bg', function( value ) {
		hootAddStyleTag( 'topann_content_bg' );
		value.bind( function( newval ) {
			hootUpdateCss( 'topann_content_bg', newval );
		} );
	} );
	wp.customize( 'topann_content_color', function( value ) {
		hootAddStyleTag( 'topann_content_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'topann_content_color', newval );
		} );
	} );

	wp.customize( 'logo_side', function( value ) {
		this.selectiveRefresh.bind("render-partials-response", function(response) {
			if ( typeof response.contents.logo_side_partial !== undefined ) {
				var location = '', logoside = '';
				wp.customize( 'menu_location', function( setting ) { location = setting.get(); });
				wp.customize( 'logo_side', function( setting ) { logoside = setting.get(); });
				logoside = logoside === 'widget-area' ? 'widget' : logoside;
				logoside = location === 'side' ? 'menu' : logoside;
				$("#header").removeClass('sitehead-side-widget sitehead-side-search sitehead-side-none sitehead-side-menu').addClass('sitehead-side-'+logoside);
			}
		});
	} );

	wp.customize( 'menu_location', function( value ) {
		value.bind( function( newval ) {
			if ( ['top','bottom','none','side'].includes(newval) ) {
				$( '#header' ).removeClass('sitehead-menu-top sitehead-menu-bottom sitehead-menu-side sitehead-menu-none').addClass('sitehead-menu-'+newval);
				// Additionally manage side as well
				var logoside;
				if ( newval === 'side' ) {
					logoside = 'menu';
				} else {
					wp.customize( 'logo_side', function( setting ) { logoside = setting.get(); });
					logoside = ['search','widget-area','none'].includes(logoside) ? logoside : 'none';
					logoside = logoside === 'widget-area' ? 'widget' : logoside;
				}
				$( '#header' ).removeClass('sitehead-side-widget sitehead-side-search sitehead-side-none sitehead-side-menu').addClass('sitehead-side-'+logoside);
			} else {
				wp.customize.preview.send( 'refresh' );
			}
		} );
	} );

	wp.customize( 'fullwidth_menu_align', function( value ) {
		value.bind( function( newval ) {
			if ( ['left','right','center'].includes(newval) ) {
				$( '#header' ).removeClass('sitehead-menualign-left sitehead-menualign-right sitehead-menualign-center').addClass('sitehead-menualign-'+newval);
			} else {
				wp.customize.preview.send( 'refresh' );
			}
		} );
	} );

	wp.customize( 'disable_table_menu', function( value ) {
		value.bind( function( newval ) {
			if (newval) $( '#header' ).removeClass('hoot-tablemenu');
			else        $( '#header' ).addClass('hoot-tablemenu');
		} );
	} );

	wp.customize( 'mobile_menu_label', function( value ) {
		$toggletext = $('.menu-toggle-text')
		value.bind( function( newval ) {
			if ( newval ) { $toggletext.text( newval ).removeClass('hootnoshow'); }
			else { $toggletext.text('').addClass('hootnoshow'); }
		} );
	} );

	wp.customize( 'mobile_submenu_click', function( value ) {
		value.bind( function( newval ) {
			var mobilesubmenuclass = (newval) ? 'mobilesubmenu-click' : 'mobilesubmenu-open';
			$( '#header' ).removeClass('mobilesubmenu-click mobilesubmenu-open').addClass(mobilesubmenuclass);
		} );
	} );

	wp.customize( 'logo_border', function( value ) {
		value.bind( function( newval ) {
			$( '#site-logo' ).removeClass('logo-border nopadding');
			if (newval == 'border' || newval == 'bordernopad')
				$( '#site-logo' ).addClass('logo-border');
			if (newval == 'bordernopad')
				$( '#site-logo' ).addClass('nopadding');
		} );
	} );

	wp.customize( 'site_title_icon', function( value ) {
		value.bind( function( newval ) {
			if ( newval )
				$( '#site-logo-text, #site-logo-custom' ).addClass('site-logo-with-icon').find('i').remove().end().find('a').prepend('<i class="' + newval + '"></i>');
			else
				$( '#site-logo-text, #site-logo-custom' ).removeClass('site-logo-with-icon').find('i').remove();
		} );
	} );

	wp.customize( 'site_title_icon_size', function( value ) {
		hootAddStyleTag( 'site_title_icon_size' );
		value.bind( function( newval ) {
			var newvalint = parseInt(newval);
			newvalint = !isNaN(newvalint) && newvalint > 0 ? newvalint+'px' : false; // don't allow 0 or negative
			hootUpdateCss( 'site_title_icon_size', newvalint, 'px' );
		} );
	} );

	var lineids = $.isArray( settingMap['customlogolineids'] ) ? settingMap['customlogolineids'] : [ 'line1', 'line2', 'line3', 'line4' ];

	wp.customize( 'logo_custom', function( value ) {
		hootAddStyleTag( 'logo_custom_line_font' );
		value.bind( function( newval ) {
			var newval = hootDeserialize(newval);
			var lineselector = lineids.map(function(id) { return '.site-title-' + id; }).join(', ');
			var $lines = $('#site-title').find(lineselector);

			if ( !newval || $lines.length !== lineids.length ) {
				// Fallback to logo partial refresh to handle changes
				var partial = wp.customize.selectiveRefresh.partial('logo_partial');
				if ( partial ) { partial.refresh(); } else { wp.customize.preview.send( 'refresh' ); }
			} else {
				var linesizearray = {};
				var linesizedefault = defaultMap['logo_custom_line_font'];
				lineids.forEach(function(lineid, index) {
					var $line = $('.site-title-' + lineid);
					var text = getMultilevelObjVal( newval, ['logo_custom', lineid, 'text'] ) || '',
						hide = getMultilevelObjVal( newval, ['logo_custom', lineid, 'sortitem_hide'] ) || false,
						font = getMultilevelObjVal( newval, ['logo_custom', lineid, 'font'] ) || false,
						size = getMultilevelObjVal( newval, ['logo_custom', lineid, 'size'] ) || 0;
					$line.html( text );
					$line.removeClass('hootnoshow');
					if ( hide === 1 || hide === '1' || ! text )
						$line.addClass('hootnoshow');
					$line.removeClass('bodyfont titlefont');
					if ( font === 'standard' ) $line.addClass('bodyfont');
					if ( font === 'heading2' ) $line.addClass('titlefont');
					var linesize = parseInt( size ) || parseInt( linesizedefault ) || 24; // Dont allow 0
					linesizearray[lineid] = linesize + 'px';
				});
				hootUpdateCss( 'logo_custom_line_font', linesizearray );

			}
		} );
	} );

	wp.customize( 'show_tagline', function( value ) {
		value.bind( function( newval ) {
			if (newval)
				$( '#site-description' ).removeClass('hootnoshow');
			else
				$( '#site-description' ).addClass('hootnoshow');
		} );
	} );

	var sticky_sitehead_live = function( screen, layout, reset=false ) {
		var tag           = screen === 'mob' ? 'mob'            : 'dtp'           ;
		var stickytag     = screen === 'dtp' ? 'stickydtp'      : 'stickymob'     ;
		var dataStickytag = screen === 'dtp' ? 'data-stickydtp' : 'data-stickymob';
		var istag         = screen === 'dtp' ? 'isdtp'          : 'ismob'         ;
		var stickyLayouts = screen === 'dtp' ?
			'stickydtp-topbar stickydtp-logo stickydtp-menu stickydtp-text stickydtp-logomenu stickydtp-logomenudiv stickydtp-logotext stickydtp-logotextdiv stickydtp-logomenutext' :
			'stickymob-topbar stickymob-logo stickymob-menu stickymob-menuleft stickymob-menuright stickymob-text stickymob-logomenu stickymob-menulogo stickymob-logotext stickymob-logotextdiv stickymob-logomenutext';

		var $topbar = $( '#topbar' ),
			$header = $( '#header' );
		var $topbarContainer = $topbar.parent('.sticky-wrapper-topbar'),
			$headerContainer = $header.parent('.sticky-wrapper-header');
		if ( reset ) {
			$topbar.removeClass( stickytag ).removeAttr( dataStickytag );
			$header.removeClass( stickytag ).removeAttr( dataStickytag );
			if ( $topbarContainer.length ) { $topbarContainer.removeClass( istag ) }
			if ( $headerContainer.length ) { $headerContainer.removeClass( istag ) }
			$topbar.removeClass(stickyLayouts);
			$topbarContainer.height('');
			$header.removeClass(stickyLayouts);
			$headerContainer.height('');
			$('body').trigger( 'resetstickyderived' );
		} else {
			var isTopbar = layout === 'topbar';
			var isHeader = ! isTopbar;
			if ( isTopbar ) {
				$topbar.addClass( stickytag ).attr( dataStickytag, stickytag + '-' + layout );
				$header.removeClass( stickytag ).removeAttr(dataStickytag);
			} else {
				$header.addClass( stickytag ).attr( dataStickytag, stickytag + '-' + layout );
				$topbar.removeClass( stickytag ).removeAttr(dataStickytag);
			}
			// code from scroller.js
			if ( isTopbar ) {
				if ( $topbarContainer.length ) { $topbarContainer.addClass( istag ) }
				if ( $headerContainer.length ) { $headerContainer.removeClass( istag ) }
			} else {
				if ( $topbarContainer.length ) { $topbarContainer.removeClass( istag ) }
				if ( $headerContainer.length ) { $headerContainer.addClass( istag ) }
			}
			if ( $topbar.hasClass('hootstuck') && $topbarContainer.length ) {
				$header.removeClass(stickyLayouts);
				$headerContainer.height('');
				$topbar.removeClass(stickyLayouts).addClass( stickytag + '-' + layout );
				$topbarContainer.height( $('#topbar').outerHeight(true) );
				$('body').trigger( 'siteheadstucked' );
			}
			if ( $header.hasClass('hootstuck') && $headerContainer.length ) {
				$topbar.removeClass(stickyLayouts);
				$topbarContainer.height('');
				$header.removeClass(stickyLayouts).addClass( stickytag + '-' + layout );
				$headerContainer.height( $('#header').outerHeight(true) );
				$('body').trigger( 'siteheadstucked' );
			}
		}
	}

	wp.customize( 'sticky_accent', function( value ) {
		value.bind( function( newval ) {
			if ( newval === 'accent' ) {
				$( '#header' ).addClass('sticky-accent');
			} else {
				$( '#header' ).removeClass('sticky-accent');
			}
		} );
	} );
	wp.customize( 'sticky_sitehead_dtp', function( value ) {
		value.bind( function( newval ) {
			var layout;
			wp.customize( 'sticky_sitehead_dtp_layout', function( setting ) { layout = setting.get(); });
			var reset = layout ? ! newval : false;
			sticky_sitehead_live( 'dtp', layout, reset );
		} );
	} );
	wp.customize( 'sticky_sitehead_dtp_layout', function( value ) {
		value.bind( function( newval ) {
			var reset = !newval;
			sticky_sitehead_live( 'dtp', newval, reset );
		} );
	} );
	wp.customize( 'sticky_sitehead_dtp_logozoom', function( value ) {
		hootAddStyleTag( 'sticky_sitehead_dtp_logozoom' );
		value.bind( function( newval ) {
			var newvalint = parseInt(newval);
			if ( !isNaN(newvalint) && newvalint > 0 && newvalint <= 100 ) { // dont allow 0
				newvalint = newvalint/100;
			} else { // shouldn't happen as range should always have a value (10-100)
				var mapDefault = parseInt( defaultMap.sticky_sitehead_dtp_logozoom );
				newvalint = !isNaN(mapDefault) && mapDefault > 0 && mapDefault <= 100 ? mapDefault/100 : 1;
			}
			hootUpdateCss( 'sticky_sitehead_dtp_logozoom', newvalint );
		} );
	} );
	// doesn't work with do_shortcode/wpautop in themeslug_sitehead_extras

	wp.customize( 'sticky_sitehead_mob', function( value ) {
		value.bind( function( newval ) {
			var layout;
			wp.customize( 'sticky_sitehead_mob_layout', function( setting ) { layout = setting.get(); });
			var reset = layout ? ! newval : false;
			sticky_sitehead_live( 'mob', layout, reset );
		} );
	} );
	wp.customize( 'sticky_sitehead_mob_layout', function( value ) {
		value.bind( function( newval ) {
			var reset = !newval;
			sticky_sitehead_live( 'mob', newval, reset );
		} );
	} );
	wp.customize( 'sticky_sitehead_mob_logozoom', function( value ) {
		hootAddStyleTag( 'sticky_sitehead_mob_logozoom' );
		value.bind( function( newval ) {
			var newvalint = parseInt(newval);
			if ( !isNaN(newvalint) && newvalint > 0 && newvalint <= 100 ) { // dont allow 0
				newvalint = newvalint/100;
			} else { // shouldn't happen as range should always have a value (10-100)
				var mapDefault = parseInt( defaultMap.sticky_sitehead_mob_logozoom );
				newvalint = !isNaN(mapDefault) && mapDefault > 0 && mapDefault <= 100 ? mapDefault/100 : 1;
			}
			hootUpdateCss( 'sticky_sitehead_mob_logozoom', newvalint );
		} );
	} );
	// doesn't work with do_shortcode/wpautop in themeslug_sitehead_extras

	wp.customize( 'box_background_color', function( value ) {
		hootAddStyleTag( 'box_background_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'box_background_color', newval );
		} );
	} );

	wp.customize( 'article_background_type', function( value ) {
		value.bind( function( newval ) {
			$article = $( '.singular-page #content-wrap, .singular-post #content-wrap');
			$article.removeClass('article-bg article-bg-whensidebar');
			if (newval === 'background')
				$article.addClass('article-bg');
			else if (newval === 'background-whensidebar')
				$article.addClass('article-bg-whensidebar');
		} );
	} );
	wp.customize( 'article_background_color', function( value ) {
		hootAddStyleTag( 'article_background_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'article_background_color', newval );
		} );
	} );
	wp.customize( 'read_more', function( value ) {
		value.bind( function( newval ) {
			if ( newval ) { $( '.theme-more-link a' ).text( newval ); }
			// Let php determine default read more text - may be different in different contexts eg. theme vs hootkit widgets
			else { wp.customize.preview.send( 'refresh' ); }
		} );
	} );
	var cacheFeatImg = {};
	var featured_image = function( context, newval ) {
		var headeroptions = [ 'staticheader-nocrop', 'staticheader', 'header' ];
		if ( ! cacheFeatImg[context] || ! headeroptions.includes( cacheFeatImg[context] ) || ! headeroptions.includes( newval ) ) {
			wp.customize.preview.send( 'refresh' );
		} else {
			var $pgheadimgwrap = $('.pgheadimg-'+context);
			if ( $pgheadimgwrap.length ) {
				var $pgheadimg = $pgheadimgwrap.children('img.pgheadimg');
				var $pgheaddiv = $pgheadimgwrap.children('div.pgheadimg');
				$pgheadimgwrap.removeClass('pgheadimg-inline pgheadimg-bg')
				if ( newval === 'staticheader-nocrop' ) {
					$pgheadimgwrap.addClass('pgheadimg-inline');
					$pgheaddiv.addClass('hootnoshow');
					$pgheadimg.removeClass('hootnoshow');
				} else {
					$pgheadimgwrap.addClass('pgheadimg-bg');
					$pgheadimg.addClass('hootnoshow');
					$pgheaddiv.removeClass('hootnoshow').removeClass('bg-parallax bg-noparallax').addClass( newval === 'header' ? 'bg-parallax' : 'bg-noparallax' );
					if ( newval === 'header' ) {
						$pgheaddiv.css('transform',''); // important to remove any leftoer inline transform from hootPgheadimgInit in hoot.theme.js else parallax css becomes redundant
					}
				}
				$(document).trigger('hootPgheadimgReinit');
			}
		}
		cacheFeatImg[context] = newval;
	}
	wp.customize( 'archive_featured_image', function( value ) {
		cacheFeatImg.archive = value.get();
		value.bind( function( newval ) {
				featured_image( 'archive', newval );
		} );
	} );
	if(!hootpload){
	wp.customize( 'post_featured_image', function( value ) {
		cacheFeatImg.post = value.get();
		value.bind( function( newval ) {
				featured_image( 'post', newval );
		} );
	} );
	}
	if(!hootpload){
	wp.customize( 'post_featured_image_page', function( value ) {
		cacheFeatImg.page = value.get();
		value.bind( function( newval ) {
				featured_image( 'page', newval );
		} );
	} );
	}

	wp.customize( 'post_prev_next_links', function( value ) {
		var cachePrevNext = value.get();
		var fixedoptions = ['fixed-text','fixed-thumb'];
		value.bind( function( newval ) {
			if ( ! cachePrevNext || fixedoptions.includes( cachePrevNext ) || fixedoptions.includes( newval ) ) {
				wp.customize.preview.send( 'refresh' );
			} else {
				var partial = wp.customize.selectiveRefresh.partial('post_prev_next_links_partial');
				if ( partial ) { partial.refresh(); } else { wp.customize.preview.send( 'refresh' ); }
			}
			cachePrevNext = newval;
		} );
	} );

	$.each( [ 'author', 'date', 'cats', 'tags', 'comments' ], function( index, metatag ) {
		wp.customize( 'meta_label_'+metatag, function( value ) {
			value.bind( function( newval ) {
				$('.entry-byline-'+metatag+' .entry-byline-label').text(newval);
			} );
		} );
	} );

	$.each( [ 'article_align', 'article_align_mob', 'gridarticle_align', 'gridarticle_align_mob' ], function( index, alignop ) {
		wp.customize( alignop, function( value ) {
			var prefix = alignop + '-';
			value.bind( function( newval ) {
				$('article.entry').removeClass( prefix+'left' + ' ' + prefix+'center' + ' ' + prefix+'right' + ' ' + prefix+'justify' ).addClass( prefix+newval );
			} );
		} );
	} );
	if(!hootpload){
	wp.customize( 'article_maxwidth', function( value ) {
		hootAddStyleTag( 'article_maxwidth' );
		value.bind( function( newval ) {
			var newvalint = parseInt(newval);
			newvalint = !isNaN(newvalint) && newvalint > 0 ? newvalint+'px' : false; // don't allow 0 or negative
			hootUpdateCss( 'article_maxwidth', newvalint, 'px' );
		} );
	} );
	wp.customize( 'article_maxwidth_nosidebar', function( value ) {
		hootAddStyleTag( 'article_maxwidth_nosidebar' );
		value.bind( function( newval ) {
			var newvalint = parseInt(newval);
			newvalint = !isNaN(newvalint) && newvalint > 0 ? newvalint+'px' : false; // don't allow 0 or negative
			hootUpdateCss( 'article_maxwidth_nosidebar', newvalint, 'px' );
		} );
	} );
	}

	wp.customize( 'footer', function( value ) {
		var structure = {
				'1-1' : [ 12, 12, 12, 12, 12, 12 ],
				'2-1' : [  6,  6, 12, 12, 12, 12 ],
				'2-2' : [  4,  8, 12, 12, 12, 12 ],
				'2-3' : [  8,  4, 12, 12, 12, 12 ],
				'3-1' : [  4,  4,  4, 12, 12, 12 ],
				'3-2' : [  6,  3,  3, 12, 12, 12 ],
				'3-3' : [  3,  6,  3, 12, 12, 12 ],
				'3-4' : [  3,  3,  6, 12, 12, 12 ],
				'4-1' : [  3,  3,  3,  3, 12, 12 ],
				'5-1' : [ 24, 24, 24, 24, 24, 12 ],
				'3-5' : [  6,  6, 12, 12, 12, 12 ],
				'4-2' : [  4,  4,  4, 12, 12, 12 ],
				'5-2' : [  3,  3,  3,  3, 12, 12 ],
				'6-2' : [ 24, 24, 24, 24, 24, 12 ],
				'3-6' : [ 12,  6,  6, 12, 12, 12 ],
				'4-3' : [ 12,  4,  4,  4, 12, 12 ],
				'5-3' : [ 12,  3,  3,  3,  3, 12 ],
				'6-3' : [ 12, 24, 24, 24, 24, 24 ],
		};
		value.bind( function( newval ) {
			var col = parseInt(newval.substr(0,1)),
				fclasses = typeof structure[newval] !== 'undefined' ? structure[newval] : structure['1-1'],
				fstyles = false;
			if ( col && !isNaN( col ) ) {
				fstyles = [];
				for ( var i = 0; i < 6; i++ ) {
					if ( i < col ) fstyles.push('block');
					else           fstyles.push('none');
				}
			}
			if ( ! fstyles ) fstyles = ['block','block','block','block','block','block'];
			$('.footer-column').removeClass('hgrid-span-12 hgrid-span-8 hgrid-span-6 hgrid-span-4 hgrid-span-3 hgrid-span-2').removeAttr("style").each(function(index){
				$(this).addClass('hgrid-span-'+fclasses[index]).css('display',fstyles[index]);
			});
		} );
	} );

	wp.customize( 'footer_flexstretch', function( value ) {
		var $area = $('#footer');
		value.bind( function( newval ) {
			if ( newval ) {
				$area.addClass('flexstretch-cols');
			} else {
				$area.removeClass('flexstretch-cols');
			}
		} );
	} );


	///////////////// Homepage Image

	$.each( [ 'minheight', 'conpad', 'imgpad', 'headsize', 'subheadsize', 'textsize', 'btnsize' ], function( index, setid ) {
		wp.customize( 'header_image_'+setid, function( value ) {
			hootAddStyleTag( 'header_image_'+setid );
			value.bind( function( newval ) {
				var newvalint = parseInt(newval);
				if ( setid === 'conpad' || setid === 'imgpad' ) {
					newvalint = !isNaN(newvalint) && newvalint >= 0 ? newvalint+'px' : false;
				} else {
					newvalint = !isNaN(newvalint) && newvalint > 0 ? newvalint+'px' : false; // don't allow 0 or negative
				}
				hootUpdateCss( 'header_image_'+setid, newvalint, 'px' );
			} );
		} );
	} );

	$.each( [ 'bg', 'headcolor', 'subheadcolor', 'textcolor', 'btncolor', 'btnbg', 'btncolor2', 'btnbg2' ], function( index, setid ) {
		wp.customize( 'header_image_'+setid, function( value ) {
			hootAddStyleTag( 'header_image_'+setid );
			value.bind( function( newval ) {
				if ( newval )
					hootUpdateCss( 'header_image_'+setid, newval );
				else
					wp.customize.preview.send( 'refresh' ); // removing css-var using hootUpdateCss will lead to css-var from last css.php come into play. whereas, in scss, we use a fallabck var for things like buttons (--hoot-buttoncolor/buttonfont) or headings(--hoot-headings-color,--hoot-subheadings-color) or text(--hoot-basefont-color). Pretty much everything except 'header_image_bg' // Hence we need to remove css-var added by hootUpdateCss AND css-var added by css.php (if any) since the last refresh/load
			} );
		} );
	} );

	$.each( [ 'conbg', 'overlay' ], function( index, setid ) {
		wp.customize( 'header_image_'+setid, function( value ) {
			var fpimgtextboxalpha = false;
			hootAddStyleTag( 'header_image_'+setid );
			value.bind( function( newval ) {
				if ( ! newval ) newval = '#ffffff00'; // treat empty as transparent
				hootUpdateCss( 'header_image_'+setid, newval );
				if ( setid === 'conbg' ) {
					var alpha0 = getHexAlpha(newval) == 0 ? 'yes' : 'no';
					if ( fpimgtextboxalpha !== alpha0 ) {
						fpimgtextboxalpha = alpha0;
						if ( alpha0 === 'yes' ) $('#frontpage-image .fpimg-textbox').addClass('fpimg-textbox-nobg');
						else if ( alpha0 === 'no' ) $('#frontpage-image .fpimg-textbox').removeClass('fpimg-textbox-nobg');
					}
				}
			} );
		} );
	} );

	wp.customize( 'frontpage_sections_enable', function( value ) {
		value.bind( function( newval ) {
			wp.customize.preview.send( 'refresh' );
		} );
	} );

	var areaids = $.isArray( settingMap['fpareaids'] ) ? settingMap['fpareaids'] : [];

	wp.customize( 'frontpage_sections', function( value ) {
		// Latest value on load OR when customize preview refreshes from a non transport>postmessage setting
		// Hence this gets updated when we refresh below on seqChanged=true
		var origSeq = hootDeserialize( wp.customize.settings.values.frontpage_sections );
		var cacheSeq = origSeq && typeof origSeq['frontpage_sections'] === 'object'
						? Object.keys(origSeq['frontpage_sections'])
						: [];

		value.bind( function( newval ) {
			var newval = hootDeserialize(newval);
			var newSeq = newval && typeof newval['frontpage_sections'] === 'object'
						? Object.keys(newval['frontpage_sections'])
						: [];
			var seqChanged = cacheSeq.length !== newSeq.length;
			if ( !seqChanged ) {
				for (var i = 0; i < newSeq.length; i++) {
					if (newSeq[i] !== cacheSeq[i]) seqChanged = true;
				}
			}

			var areaselector = areaids.map(function(areaid) {
					var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
					return '#frontpage-' + areapageid;
				}).join(', ');
			var $areas = $('#main').find(areaselector);

			if ( !newval || $areas.length !== areaids.length || seqChanged ) {
				// Fallback to preview refresh to handle changes
				wp.customize.preview.send( 'refresh' );
			} else {
				areaids.forEach(function(areaid, index) {
					var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
					var $area = $('#frontpage-' + areapageid);
					var hide = getMultilevelObjVal( newval, ['frontpage_sections', areaid, 'sortitem_hide'] ) || false;
					$area.removeClass('hootnoshow');
					if ( hide === 1 || hide === '1' ) {
						$area.addClass('hootnoshow');
					}
				});

			}
		} );
	} );

	// Homepage Content - Title
	wp.customize( 'frontpage_sectionbg_content-title', function( value ) {
		var $areatitle = $('#frontpage-page-content .frontpage-page-content-title');
		var $areahead = $areatitle.find('h3');
		value.bind( function( newval ) {
			if(newval) {
				$areatitle.removeClass('hootnoshow');
				$areahead.html(newval);
			} else {
				$areatitle.addClass('hootnoshow');
				$areahead.html('');
			}
		} );
	} );

	var fpfontselector = typeof settingMap['fpfontselector'] === 'string' ? settingMap['fpfontselector'] : false;

	$.each( areaids, function( index, areaid ) { if ( areaid !== 'image' ) {

		if ( areaid !== 'content' ) {
		wp.customize( 'frontpage_sectionbg_'+areaid+'-columns', function( value ) {
			var areapageid = areaid;
			var $area = $('#frontpage-' + areapageid);
			value.bind( function( newval ) {
				var colArr = hootResolveFpCols( newval );
				var $columns = $area.find('.frontpage-areacol');
				$columns.removeClass('hootnoshow hgrid-span-12 hgrid-span-9 hgrid-span-8 hgrid-span-6 hgrid-span-4 hgrid-span-3').each(function(index){
					if ( colArr[index] )
						$(this).addClass('hgrid-span-'+colArr[index]);
					else
						$(this).addClass('hootnoshow');
				});
				window.dispatchEvent(new Event('resize'));
				if ( $area.find('.lSSlideOuter').length > 0 ) {
					setTimeout(() => { wp.customize.preview.send( 'refresh' ) },500);
				}
			} );
		} );
		}

		wp.customize( 'frontpage_sectionbg_'+areaid+'-grid', function( value ) {
			var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
			var $area = $('#frontpage-' + areapageid);
			value.bind( function( newval ) {
				$area.removeClass('frontpage-area-stretch frontpage-area-boxed');
				if ( newval === 'stretch' ) {
					$area.addClass('frontpage-area-stretch');
				} else {
					$area.addClass('frontpage-area-boxed');
				}
			} );
		} );

		if ( areaid !== 'content' ) {
		wp.customize( 'frontpage_sectionbg_'+areaid+'-flexstretch', function( value ) {
			var areapageid = areaid;
			var $area = $('#frontpage-' + areapageid);
			value.bind( function( newval ) {
				if ( newval ) {
					$area.addClass('flexstretch-cols');
				} else {
					$area.removeClass('flexstretch-cols');
				}
			} );
		} );
		}

		wp.customize( 'frontpage_sectionbg_'+areaid+'-type', function( value ) {
			var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
			value.bind( function( newval ) {
				var $area = $('#frontpage-'+areapageid),
					color = '',
					image = '',
					parallax = 0;
				$area.removeClass('bg-parallax bg-noparallax area-bgcolor')
					.removeClass('module-bg-image module-bg-color module-bg-none')
					.removeAttr("style");
				if ( newval == 'none' ) {
					$area.addClass('module-bg-none');
				} else if ( newval == 'color' ) {
					$area.addClass('module-bg-color area-bgcolor');
					wp.customize( 'frontpage_sectionbg_'+areaid+'-color', function( setting ) { color = setting.get(); });
					if ( color ) $area.css('background-color',color);
				}
				else if ( newval == 'image' ) {
					$area.addClass('module-bg-image')
					wp.customize( 'frontpage_sectionbg_'+areaid+'-image', function( setting ) { image = setting.get(); });
					if ( image ) $area.css('background-image','url('+image+')');
					wp.customize( 'frontpage_sectionbg_'+areaid+'-parallax', function( setting ) { parallax = setting.get(); });
					$area.addClass(parallax ? 'bg-parallax' : 'bg-noparallax');
				}
			} );
		} );

		wp.customize( 'frontpage_sectionbg_'+areaid+'-color', function( value ) {
			var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
			value.bind( function( newval ) {
				var type = '';
				wp.customize( 'frontpage_sectionbg_'+areaid+'-type', function( setting ) { type = setting.get(); });
				if ( type=='color' ) $('#frontpage-'+areapageid).css('background-color',newval);
			} );
		} );

		wp.customize( 'frontpage_sectionbg_'+areaid+'-image', function( value ) {
			var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
			value.bind( function( newval ) {
				var type = '',
					parallax = 0,
					$frontpagearea = $('#frontpage-' + areapageid);
				wp.customize( 'frontpage_sectionbg_'+areaid+'-parallax', function( setting ) { parallax = setting.get(); });
				wp.customize( 'frontpage_sectionbg_'+areaid+'-type', function( setting ) { type = setting.get(); });
				if (type === 'image')
					$frontpagearea
						.css('background-image', newval ? 'url(' + newval + ')' : 'none')
						.removeClass('bg-parallax bg-noparallax')
						.addClass(parallax ? 'bg-parallax' : 'bg-noparallax');
			} );
		} );

		wp.customize( 'frontpage_sectionbg_'+areaid+'-parallax', function( value ) {
			var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
			value.bind( function( newval ) {
				var type = 0,
					$frontpagearea = $('#frontpage-' + areapageid);
				wp.customize( 'frontpage_sectionbg_'+areaid+'-type', function( setting ) { type = setting.get(); });
				if ( type == 'image' )
					$frontpagearea
						.removeClass('bg-parallax bg-noparallax')
						.addClass(newval ? 'bg-parallax' : 'bg-noparallax');
			} );
		} );

		wp.customize( 'frontpage_sectionbg_'+areaid+'-font', function( value ) {
			var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
			var $fpareaStyle = $('#hoot-customize-frontpage-'+areapageid);
			value.bind( function( newval ) {
				if ( ! fpfontselector ) { wp.customize.preview.send( 'refresh' ); }
				var css = '';
				var fontcolor = '';
				wp.customize( 'frontpage_sectionbg_'+areaid+'-fontcolor', function( setting ) { fontcolor = setting.get(); });
				if ( fontcolor ) { switch (newval) {
					case 'color':
						css = fpfontselector.replace( '.varid', '.frontpage-'+areapageid ) + '{color:'+fontcolor+'}';
						break;
					case 'force':
						css = fpfontselector.replace( '.varid', '#frontpage-'+areapageid ) + '{color:'+fontcolor+'}';
						break;
				} }
				$fpareaStyle.html( css ); // css is empty if no fontcolor, or if font is set to 'theme'
			} );
		} );

		wp.customize( 'frontpage_sectionbg_'+areaid+'-fontcolor', function( value ) {
			var areapageid = ( areaid == 'content' ) ? 'page-content' : areaid;
			var $fpareaStyle = $('#hoot-customize-frontpage-'+areapageid);
			value.bind( function( newval ) {
				if ( ! fpfontselector ) { wp.customize.preview.send( 'refresh' ); }
				var css = '';
				var font = '';
				wp.customize( 'frontpage_sectionbg_'+areaid+'-font', function( setting ) { font = setting.get(); });
				if ( newval ) { switch (font) {
					case 'color':
						css = fpfontselector.replace( '.varid', '.frontpage-'+areapageid ) + '{color:'+newval+'}';
						break;
					case 'force':
						css = fpfontselector.replace( '.varid', '#frontpage-'+areapageid ) + '{color:'+newval+'}';
						break;
				} }
				$fpareaStyle.html( css ); // css is empty if no fontcolor, or if font is set to 'theme'
			} );
		} );

	} } );


	wp.customize( 'accent_color', function( value ) {
		hootAddStyleTag( 'accent_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'accent_color', newval );
		} );
	} );
	wp.customize( 'accent_font', function( value ) {
		hootAddStyleTag( 'accent_font' );
		value.bind( function( newval ) {
			hootUpdateCss( 'accent_font', newval );
		} );
	} );
	wp.customize( 'button_color', function( value ) {
		hootAddStyleTag( 'button_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'button_color', newval );
		} );
	} );
	wp.customize( 'button_font', function( value ) {
		hootAddStyleTag( 'button_font' );
		value.bind( function( newval ) {
			hootUpdateCss( 'button_font', newval );
		} );
	} );
	wp.customize( 'link_color', function( value ) {
		hootAddStyleTag( 'link_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'link_color', newval );
		} );
	} );
	wp.customize( 'link_hover_color', function( value ) {
		hootAddStyleTag( 'link_hover_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'link_hover_color', newval );
		} );
	} );


	wp.customize( 'topbar_grid', function( value ) {
		value.bind( function( newval ) {
			if (newval == 'stretch')
				$('#topbar > div').removeClass('hgrid').addClass('hgrid-stretch');
			else
				$('#topbar > div').removeClass('hgrid-stretch').addClass('hgrid');
		} );
	} );
	wp.customize( 'below_sitehead_grid', function( value ) {
		value.bind( function( newval ) {
			if (newval == 'stretch')
				$( '#below-sitehead' ).removeClass('below-sitehead-boxed').addClass('below-sitehead-stretch');
			else
				$( '#below-sitehead' ).removeClass('below-sitehead-stretch').addClass('below-sitehead-boxed');
		} );
	} );
	wp.customize( 'subfooter_grid', function( value ) {
		value.bind( function( newval ) {
			if (newval == 'stretch')
				$('#sub-footer > div').removeClass('hgrid').addClass('hgrid-stretch');
			else
				$('#sub-footer > div').removeClass('hgrid-stretch').addClass('hgrid');
		} );
	} );


	$.each( [ 'logo_margin', 'topbar_padding', 'below_sitehead_padding', 'subfooter_padding', 'footer_padding', 'postfooter_padding' ], function( index, setid ) {
		wp.customize( setid, function( value ) {
			hootAddStyleTag( setid );
			value.bind( function( newval ) {
				allowNegative = ( setid === 'logo_margin' ) ? true : false;
				var newval = hootResolveSpacers(newval, allowNegative);
				if ( ! newval ) { // This should not happen!
					if ( typeof defaultMap[setid] === 'object' && defaultMap[setid] !== null ) {
						newval = JSON.stringify( defaultMap[setid] );
						newval = hootResolveSpacers(newval, allowNegative);
					}
					if ( ! newval ) { // last resort.
						newval = { media:{desktop:'0px',tablet:'0px',mobile:'0px'} };
					}
				}
				hootUpdateCss( setid, newval );
			} );
		} );
	} );

	wp.customize( 'logo_background', function( value ) {
		var logobgalpha = false;
		hootAddStyleTag( 'logo_background' );
		value.bind( function( newval ) {
			if ( ! newval ) newval = '#ffffff00'; // treat empty as transparent
			hootUpdateCss( 'logo_background', newval );
			var alpha0 = getHexAlpha(newval) == 0 ? 'yes' : 'no';
			if ( logobgalpha !== alpha0 ) {
				logobgalpha = alpha0;
				if ( alpha0 === 'yes' ) $('#site-logo').removeClass('with-background');
				else if ( alpha0 === 'no' ) $('#site-logo').addClass('with-background');
			}
		} );
	} );
	wp.customize( 'logo_color', function( value ) {
		hootAddStyleTag( 'logo_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'logo_color', newval );
		} );
	} );

	if(!hootpload){
	wp.customize( 'topbar_colorscheme', function( value ) {
		value.bind( function( newval ) {
			$('#topbar').removeClass('topbaraccent topbarscheme topbarscheme-darkfont topbarscheme-lightfont topbarscheme-light topbarscheme-dark');
			if ( newval === 'accent' )
				$('#topbar').addClass('topbaraccent');
			else if ( newval === 'darkfont' )
				$('#topbar').addClass('topbarscheme topbarscheme-darkfont');
			else if ( newval === 'lightfont' )
				$('#topbar').addClass('topbarscheme topbarscheme-lightfont');
			else if ( newval === 'light' )
				$('#topbar').addClass('topbarscheme topbarscheme-light');
			else if ( newval === 'dark' )
				$('#topbar').addClass('topbarscheme topbarscheme-dark');
		} );
	} );
	}
	if(!hootpload){
	wp.customize( 'menu_colorscheme', function( value ) {
		value.bind( function( newval ) {
			$('#page-wrapper').removeClass('with-menubg menuscheme-accent menuscheme-darkfont menuscheme-lightfont menuscheme-light menuscheme-dark');
			if ( newval === 'accent' )
				$('#page-wrapper').addClass('with-menubg menuscheme-accent');
			else if ( newval === 'darkfont' )
				$('#page-wrapper').addClass('menuscheme-darkfont');
			else if ( newval === 'lightfont' )
				$('#page-wrapper').addClass('menuscheme-lightfont');
			else if ( newval === 'light' )
				$('#page-wrapper').addClass('with-menubg menuscheme-light');
			else if ( newval === 'dark' )
				$('#page-wrapper').addClass('with-menubg menuscheme-dark');
		} );
	} );
	}

	if(!hootpload){
	wp.customize( 'heading_size', function( value ) {
		hootAddStyleTag( 'heading_size' );
		value.bind( function( newval ) {
			var henum = typeof defaultMap['heading_size_enum'] === 'object' && typeof defaultMap['heading_size_enum'][newval] === 'object' ? defaultMap['heading_size_enum'][newval] : {};
			hootUpdateCss( 'heading_size', henum );
		} );
	} );
	}

	var betterfontcontrols = [ 'logo_font', 'heading_font', 'subheading_font', 'body_font' ];
	if(hootpload){
		betterfontcontrols.push('tagline_font');
		betterfontcontrols.push('nav_menu_font');
		betterfontcontrols.push('nav_dropdown_font');
		betterfontcontrols.push('h1_font');
		betterfontcontrols.push('h2_font');
		betterfontcontrols.push('h3_font');
		betterfontcontrols.push('h4_font');
		betterfontcontrols.push('h5_font');
		betterfontcontrols.push('h6_font');
		betterfontcontrols.push('widgettitle_font');
		betterfontcontrols.push('footer_widgettitle_font');
		betterfontcontrols.push('footer_font');
	}
	$.each( betterfontcontrols, function( index, setid ) {
		wp.customize( setid, function( value ) {
			// Latest value on load OR when customize preview refreshes from a non transport>postmessage setting
			// Hence this gets updated when we refresh below on seqChanged=true
			var origVal = hootDeserialize( wp.customize.settings.values[ setid ] );
			origVal = typeof origVal === 'object' && origVal !== null ? origVal : {};
			var origFace = origVal.face ? origVal.face : '',
				origSubsets = Array.isArray( origVal.subsets ) ? origVal.subsets : [],
				origWeight = ! isNaN( Number(origVal.weight) ) ? origVal.weight : '';

			hootAddStyleTag( setid );
			hootAddStyleTag( setid + '-size' );
			value.bind( function( newval ) {
				var newval = hootDeserialize( newval );
				if ( typeof newval !== 'object' || newval === null ) { // This should not happen!
					wp.customize.preview.send( 'refresh' );
				} else {
					var needRefresh = false,
						constructVal = {},
						isGfont = newval.face && ! [ 'inherit', 'Inherit', 'Arial', 'Helvetica', 'Verdana', 'Trebuchet MS', 'Georgia', 'Times New Roman', 'Tahoma', 'Courier' ].includes( newval.face );

					// Check if face/subsets/weight changes and requires refresh
					if ( isGfont ) {
						if ( newval.face !== origFace ) {
							needRefresh = true;
						}
						if ( ! needRefresh ) {
							if ( Number( newval.weight ) !== Number( origWeight ) ) {
								if ( ! [ 400, 0 ].includes( Number( newval.weight ) ) ) {
									needRefresh = true;
								}
							}
						}
						if ( ! needRefresh ) {
							if ( Array.isArray( newval.subsets ) ) {
								var allIn = newval.subsets.every( function( val ) { return origSubsets.includes( val ); } );
								if ( ! allIn ) {
									needRefresh = true;
								}
							}
						}
						if ( needRefresh ) {
							wp.customize.preview.send( 'refresh' );
							return;
						}
					}
					if ( ! isGfont ) {
						var family = newval.face ? (
							newval.face.includes(' ') ? '"' + newval.face + '"' : newval.face // its important to NOT add "" to inherit (else it wont work)
							) : '';
						family += family && newval.category ? ', ' + newval.category : '';
						if ( family ) constructVal.family = family;
					}
					[ 'color', 'lheight', 'lspace', 'weight', 'style', 'trans', 'deco' ].forEach(function (key) {
						// settings may not have all keys
						if ( key === 'lheight' ) {
							if (newval[key]) constructVal[key] = newval[key] + 'em';
						} else if ( key === 'lspace' ) {
							if (newval[key] || newval[key] === 0 || newval[key] === '0') constructVal[key] = newval[key] + 'px';
						} else if ( key === 'color' ) {
							if (newval[key]) constructVal[key] = newval[key];
						} else {
							if (newval[key]) constructVal[key] = newval[key];
							else if (newval[key] === 0 || newval[key] === '0') constructVal[key] = 'inherit';
						}
					});
					hootUpdateCss( setid, constructVal );

					if ( 'size' in newval ) {
						if ( typeof newval.size === 'object' ) {
							var newSize = hootResolveRange( newval.size, 'px', false, false );
							newSize = newSize ? newSize : { media:{desktop:false,tablet:false,mobile:false} }; // This should not happen! // should be an object with media
							hootUpdateCss( setid + '-size', newSize );
						} else {
							var newSize = parseInt(newval.size);
							if ( newSize )
								hootUpdateCss( setid + '-size', newSize + 'px' );
							else
								wp.customize.preview.send( 'refresh' ); // This should not happen!
						}
					}

				}
			} );
		} );
	} );

	wp.customize( 'topbar_align', function( value ) {
		value.bind( function( newval ) {
			if ( newval === 'center' ) {
				$('.topbar-inner').addClass('hootflex-center');
				$('#topbar-left').removeClass('topbar-left').addClass('topbar-center');
				$('#topbar-right').removeClass('topbar-right').addClass('topbar-center');
			} else {
				$('.topbar-inner').removeClass('hootflex-center');
				$('#topbar-left').removeClass('topbar-center').addClass('topbar-left');
				$('#topbar-right').removeClass('topbar-center').addClass('topbar-right');
			}
		} );
	} );
	wp.customize( 'below_sitehead_align', function( value ) {
		value.bind( function( newval ) {
			if ( newval === 'center' ) {
				$('.below-sitehead-inner').addClass('hootflex-center');
				$('#below-sitehead-left').removeClass('below-sitehead-left').addClass('below-sitehead-center');
				$('#below-sitehead-right').removeClass('below-sitehead-right').addClass('below-sitehead-center');
			} else {
				$('.below-sitehead-inner').removeClass('hootflex-center');
				$('#below-sitehead-left').removeClass('below-sitehead-center').addClass('below-sitehead-left');
				$('#below-sitehead-right').removeClass('below-sitehead-center').addClass('below-sitehead-right');
			}
		} );
	} );

	wp.customize( 'belowsh_scheme', function( value ) {
		value.bind( function( newval ) {
			$bsh = $( '#below-sitehead' );
			$bsh.removeClass('below-sitehead-scheme below-sitehead-dark below-sitehead-light below-sitehead-custom');
			if (newval === 'dark') {
				$bsh.addClass('below-sitehead-scheme below-sitehead-dark');
			} else if (newval === 'light') {
				$bsh.addClass('below-sitehead-scheme below-sitehead-light');
			} else if (newval === 'custom') {
				$bsh.addClass('below-sitehead-scheme below-sitehead-custom');
			}
		} );
	} );
	wp.customize( 'belowsh_bg', function( value ) {
		hootAddStyleTag( 'belowsh_bg' );
		value.bind( function( newval ) {
			hootUpdateCss( 'belowsh_bg', newval );
		} );
	} );
	wp.customize( 'belowsh_color', function( value ) {
		hootAddStyleTag( 'belowsh_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'belowsh_color', newval );
		} );
	} );
	wp.customize( 'borderradius', function( value ) {
		hootAddStyleTag( 'borderradius' );
		value.bind( function( newval ) {
			var newval = parseInt(newval);
			newval = !isNaN(newval) && newval >= 0 ? newval : 0; // don't allow negative
			if ( newval > 50 )
				$('.singular-page #content-wrap, .singular-post #content-wrap').addClass('largeradiusactive');
			else
				$('.singular-page #content-wrap, .singular-post #content-wrap').removeClass('largeradiusactive');

			hootUpdateCss( 'borderradius', {
				base:      newval+'px',
				small:     newval >= 2  ? (newval-2)+'px' : '0px',
				medium:    newval != 0  ? (newval+2)+'px' : '0px',
				big:       newval != 0  ? (newval+2)+'px' : '0px',
				limit12:   newval <= 12 ? newval+'px'     : '12px',
				limit20:   newval <= 20 ? newval+'px'     : '20px',
				limit50:   newval <= 50 ? newval+'px'     : '50px'
			} );
		});
	} );
	wp.customize( 'buttonradius', function( value ) {
		hootAddStyleTag( 'buttonradius' );
		value.bind( function( newval ) {
			var newval = parseInt(newval);
			newval = !isNaN(newval) && newval >= 0 ? newval : 0; // don't allow negative
			hootUpdateCss( 'buttonradius', newval+'px' );
		});
	} );

	var betterbgcontrols = [ 'site_background' ];
	var betterbgtargets = { site_background : $('body') };
	if(hootpload){
		betterbgcontrols.push('header_background');
		betterbgtargets['header_background'] = $('#header');
		betterbgcontrols.push('footer_background');
		betterbgtargets['footer_background'] = $('#footer');
	}
	$.each( betterbgcontrols, function( index, setid ) {
		var ctrlid = setid === 'site_background' ? 'background' : setid;
		hootAddStyleTag( setid + '_style' );
		hootAddStyleTag( setid + '_overlay' );
		hootAddStyleTag( setid );

		wp.customize( ctrlid + '-color', function( value ) {
			value.bind( function( newval ) {
				hootUpdateCss( setid, newval );
			} );
		} );
		wp.customize( ctrlid + '-overlay', function( value ) {
			value.bind( function( newval ) {
				if ( betterbgtargets[setid].length ) {
					var alpha0 = getHexAlpha(newval) == 0 ? true : false;
					if ( ! alpha0 ) {
						var blendClass;
						wp.customize( ctrlid + '-overlayblend', function( setting ) { blendClass = setting.get(); });
						blendClass = blendClass ? ' hootoverlayblend' : '';
						betterbgtargets[setid].addClass('hootoverlay' + blendClass);
					} else {
						betterbgtargets[setid].removeClass('hootoverlay hootoverlayblend');
					}
				}
				hootUpdateCss( setid + '_overlay', newval );
			} );
		} );
		wp.customize( ctrlid + '-overlayblend', function( value ) {
			value.bind( function( newval ) {
				if ( betterbgtargets[setid].length ) {
					if ( newval ) betterbgtargets[setid].addClass('hootoverlayblend');
					else          betterbgtargets[setid].removeClass('hootoverlayblend');
				} else {
					wp.customize.preview.send( 'refresh' );
				}
			} );
		} );
		wp.customize( ctrlid + '-type', function( value ) {
			value.bind( function( newval ) {
				if ( newval === 'predefined' ) {
					var patt;
					wp.customize( ctrlid + '-pattern', function( setting ) { patt = setting.get(); });
					hootUpdateBgPatt( setid + '_style', patt );
				} else if ( newval === 'custom' ) {
					var bgimg;
					wp.customize( ctrlid + '-image', function( setting ) { bgimg = setting.get(); });
					hootUpdateBgImg( setid + '_style', ctrlid, 'bgimg', bgimg );
				}
			} );
		} );
		wp.customize( ctrlid + '-pattern', function( value ) {
			value.bind( function( newval ) {
				hootUpdateBgPatt( setid + '_style', newval );
			} );
		} );
		wp.customize( ctrlid + '-image', function( value ) {
			value.bind( function( newval ) {
				hootUpdateBgImg( setid + '_style', ctrlid, 'bgimg', newval );
			} );
		} );
		wp.customize( ctrlid + '-repeat', function( value ) {
			value.bind( function( newval ) {
				hootUpdateBgImg( setid + '_style', ctrlid, 'bgrepeat', newval );
			} );
		} );
		wp.customize( ctrlid + '-position', function( value ) {
			value.bind( function( newval ) {
				hootUpdateBgImg( setid + '_style', ctrlid, 'bgpos', newval );
			} );
		} );
		wp.customize( ctrlid + '-attachment', function( value ) {
			value.bind( function( newval ) {
				hootUpdateBgImg( setid + '_style', ctrlid, 'bgatch', newval );
			} );
		} );
		wp.customize( ctrlid + '-size', function( value ) {
			value.bind( function( newval ) {
				hootUpdateBgImg( setid + '_style', ctrlid, 'bgsize', newval );
			} );
		} );
	});
if(hootpload){


	/*** Colors ***/

	wp.customize( 'topbar_background', function( value ) {
		hootAddStyleTag( 'topbar_background' );
		hootAddStyleTag( 'stucktopbar_background' );
		value.bind( function( newval ) {
			hootUpdateCss( 'topbar_background', newval );
			var stuckval = newval,
				alpha0 = getHexAlpha(newval) == 0 ? true : false;
			if ( alpha0 ) {
				wp.customize( 'background-color', function( setting ) { stuckval = setting.get(); });
			}
			hootUpdateCss( 'stucktopbar_background', stuckval );
		} );
	} );
	wp.customize( 'topbar_color', function( value ) {
		hootAddStyleTag( 'topbar_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'topbar_color', newval );
		} );
	} );

	wp.customize( 'header_color', function( value ) {
		hootAddStyleTag( 'header_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'header_color', newval );
		} );
	} );

	wp.customize( 'menu_background', function( value ) {
		hootAddStyleTag( 'menu_background' );
		var origValue = value.get(),
			origAlpha = getHexAlpha(origValue) == 0 ? 'yes' : 'no';
		value.bind( function( newval ) {
			if ( ! newval ) newval = '#ffffff00'; // treat empty as transparent
			var alpha0 = getHexAlpha(newval) == 0 ? 'yes' : 'no';
			if ( origAlpha !== alpha0 ) {
				origAlpha = alpha0;
				wp.customize.preview.send( 'refresh' );
			} else {
				hootUpdateCss( 'menu_background', newval );
				// if ( alpha0 === 'yes' ) $('#page-wrapper').removeClass('with-menubg');
				// else if ( alpha0 === 'no' ) $('#page-wrapper').addClass('with-menubg');
			}
		} );
	} );
	wp.customize( 'menu_icons_color', function( value ) {
		hootAddStyleTag( 'menu_icons_color' );
		value.bind( function( newval ) {
			hootUpdateCss( 'menu_icons_color', newval );
		} );
	} );
	wp.customize( 'menu_dropdown_background', function( value ) {
		hootAddStyleTag( 'menu_dropdown_background' );
		value.bind( function( newval ) {
			// if empty, let it fallback to default // if transparent, trust user to know what they are doing - This color is Not used in responsive
			hootUpdateCss( 'menu_dropdown_background', newval );
		} );
	} );

	wp.customize( 'subfooter_background', function( value ) {
		hootAddStyleTag( 'subfooter_background' );
		value.bind( function( newval ) {
			// if empty, let it fallback to default // if transparent, trust user to know what they are doing
			hootUpdateCss( 'subfooter_background', newval );
		} );
	} );


	/*** Typography ***/

	wp.customize( 'contexttypo', function( value ) {
		hootAddStyleTag( 'contexttypo-fpwdgt' );
		hootAddStyleTag( 'contexttypo-loop' );
		hootAddStyleTag( 'contexttypo-loop-s' );
		hootAddStyleTag( 'contexttypo-archvpost' );
		var origVal = value.get();
		origVal = hootDeserialize( origVal );
		var origEnable = origVal && typeof origVal === 'object' && origVal.enable ? origVal.enable : false;
		value.bind( function( newval ) {
			var valobj = hootDeserialize(newval),
				needRefresh = false;
			if ( valobj && typeof valobj === 'object' ) {
				var newEnable = valobj.enable ? valobj.enable : false;
				if ( origEnable !== newEnable ) {
					origEnable = newEnable;
					needRefresh = true;
				} else {
					var choicesArray = Object.keys(valobj).filter(function(key) { return key !== 'enable'; });
					choicesArray.forEach(function(choicekey) {
						if ( typeof valobj[choicekey] === 'object' && valobj[choicekey].size ) {
							if ( typeof valobj[choicekey].size === 'number' || typeof valobj[choicekey].size === 'string' ) { // non media query
								cval = parseInt( valobj[choicekey].size ) + 'px';
								hootUpdateCss( 'contexttypo-'+choicekey, cval, 'px' );
							} else if ( typeof valobj[choicekey].size === 'object' ) { // media query based
								var cval = hootResolveRange( valobj[choicekey].size, 'px', false, false ); // allowZero,allowNegative
								if ( ! cval ) { // This should not happen! // should be an object with media
									cval = { media:{desktop:false,tablet:false,mobile:false} };
								}
								hootUpdateCss( 'contexttypo-'+choicekey, cval, 'px' );
							} else { needRefresh = true; }
						} else { needRefresh = true; }
					});
				}
			} else { needRefresh = true; }
			if ( needRefresh ) wp.customize.preview.send( 'refresh' );
		} );
	} );

}

} )( jQuery );