/***************************************************************************
 *
 * 	----------------------------------------------------------------------
 * 						DO NOT EDIT THIS FILE
 *	----------------------------------------------------------------------
 *                      Theme Customizer Scripts
 *  				    Copyright (C) Themify
 *
 *	----------------------------------------------------------------------
 *
 ***************************************************************************/

(function ($) {

	'use strict';
	var styles = [];
	// Google Font Loader
	var wf = document.createElement('script');
	wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js';
	wf.type = 'text/javascript';
	wf.async = 'true';
	var s = document.getElementsByTagName('script')[0];
	s.parentNode.insertBefore(wf, s);

	// Convert hexadecimal color to RGB. Receives string and returns object
	function hexToRgb(hex) {
		var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		return result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : null;
	}



	function getColor(values) {
		if (!values.color || 'undefined' === typeof values.color || ('undefined' !== typeof values.transparent && 'transparent' === values.transparent)) {
			return false;
		}else if(values.color.indexOf('--')===0){
			return 'var('+values.color+')';
		}
		else {
			var alpha = values.opacity ? values.opacity : 1;
			if (alpha < 1) {
				var rgb = hexToRgb(values.color);
			}
			return alpha < 1 ? 'rgba( ' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + alpha + ' )' : '#' + (values.color);
		}

	}

	// Set dimension by side, like padding or margin.
	function getDimension(side) {
		// Check if auto was set
		if (side.auto && 'auto' === side.auto) {
			return side.auto;
		} else if (side.width) {
			// Dimension Width
			return  side.width + (side.unit && 'px' !== side.unit ? side.unit : 'px');
		}
		return false;
	}

	// Get border properties.
	function getBorder(borderSide) {
		var $color = getColor(borderSide);
		return borderSide.style && 'none' !== borderSide.style && borderSide.width
			? borderSide.width + 'px ' + borderSide.style + ( $color ? ' ' + $color : '' )
			: borderSide.style && 'none' === borderSide.style ? 'none' : false;
	}

	function themifyParseJSON(data, device) {
		device = device || parent.wp.customize.previewedDevice.get();
		var rawJson = JSON.parse( data ) || {},
			jsonDesktop = _.omit( rawJson, ['tablet_landscape', 'tablet', 'mobile'] ),
			currentDeviceData, copyData;

		if ( 'desktop' !== device ) {
			currentDeviceData = rawJson[ device ] || {};
		}

		if ( 'mobile' === device ) {
			copyData = _.extend( jsonDesktop, rawJson['tablet'] );
		} else if ( 'tablet' === device ) {
			copyData = _.extend( jsonDesktop, rawJson['tablet_landscape'] );
		} else if ( 'tablet_landscape' === device ) {
			copyData = jsonDesktop;
		}

		if ( 'desktop' !== device ) {
			return _.extend(copyData, currentDeviceData);
		} else {
			return rawJson;
		}
	}

	const apiResponsiveControl = {
		init() {
			$(document)
				.on( 'themify-responsive-preview-background', this.controlBackground )
				.on( 'themify-responsive-preview-color-control', this.controlColor )
				.on( 'themify-responsive-preview-fonts-control', this.controlFonts )
				.on( 'themify-responsive-preview-border-control', this.controlBorder )
				.on( 'themify-responsive-preview-margin-control', this.controlMargin )
				.on( 'themify-responsive-preview-padding-control', this.controlMargin ) // use same control handler as margin
				.on( 'themify-responsive-preview-logo-control', this.controlLogo )
				.on( 'themify-responsive-preview-width-control', this.controlWidth )
		},

		controlBackground( event, model, currentData ) {
			var $transparent = $('.color-transparent', model.container),
				$fixedBg = $( '.fixed-bg input[type="checkbox"]', model.container ),
				$noimage = $('.disable-control', model.container),
				$hideElements = $('.open-media-wrap, .image-label, .background-style, .background-position', model.container),
				$preview = $('.themify_control_preview', model.container);

			var values = themifyParseJSON( currentData, model.getCurrentDevice() ),
				isTransparent = 'transparent' === values.transparent ? true : false,
				isBgFixed = 'fixed' === values.fixedbg,
				isNoImage = 'noimage' === values.noimage ? true : false,
				isImgSrc = values.src && '' !== values.src ? true : false;

			apiResponsiveControl._colorChange( model, values );

			$transparent.prop('checked', isTransparent);
			if ( isTransparent ) {
				$transparent.parent().prev().addClass('transparent');
			} else {
				$transparent.parent().prev().removeClass('transparent');
			}

			$fixedBg.prop( 'checked', isBgFixed );

			$noimage.prop('checked', isNoImage);
			if ( isNoImage ) {
				$hideElements.stop().hide();
			} else {
				$hideElements.stop().show();
			}

			apiResponsiveControl._dropdownChange( $('.position-style', model.container), values, 'position' );
			apiResponsiveControl._dropdownChange( $('.image-style', model.container), values, 'style' );

			if ( isImgSrc ) {
				var $imgPreview = $('<a href="#" class="remove-image ti-close"></a><img src="' + values.src + '" />').css('display', 'inline-block');
				$preview.html($imgPreview).show();
			} else {
				$preview.html('');
			}  
		},

		controlColor( event, model, currentData) {
			var values = themifyParseJSON( currentData, model.getCurrentDevice() );
			apiResponsiveControl._colorChange( model, values );
		},

		controlFonts( event, model, currentData ) {
			var values = themifyParseJSON( currentData, model.getCurrentDevice() );
			apiResponsiveControl._fontStyleChange( model, values );
			apiResponsiveControl._textTransformChange( model, values );
			apiResponsiveControl._textAlign( model, values );

			apiResponsiveControl._inputChange( $('.font_size_num', model.container), values, 'sizenum' );
			apiResponsiveControl._dropdownChange( $('.font_size_unit', model.container), values, 'sizeunit' );
			apiResponsiveControl._fontFamilyChange( $('.themify_font_family', model.container ), values );

			apiResponsiveControl._inputChange( $('.font_line_num', model.container), values, 'linenum' );
			apiResponsiveControl._dropdownChange( $('.font_line_unit', model.container), values, 'lineunit' );
			apiResponsiveControl._inputChange( $('.letter_spacing', model.container), values, 'letterspacing' );
			apiResponsiveControl._dropdownChange( $('.letter_spacing_unit', model.container), values, 'letterspacingunit' );
			apiResponsiveControl._dropdownChange( $('.font_weight_select', model.container), values, 'weight' );
		},

		controlBorder( event, model, currentData ) {
			var values = themifyParseJSON( currentData, model.getCurrentDevice() );

			apiResponsiveControl._hideComponentSameChange( $('.same', model.container), model, values );
			apiResponsiveControl._borderColorChange( model, values );
			apiResponsiveControl._dropdownBorderSameChange( $('.border-style', model.container), model, values );
			apiResponsiveControl._dimensionSameChange( $('.dimension-width', model.container), model, values );
		},

		controlMargin( event, model, currentData ) {
			var values = themifyParseJSON( currentData, model.getCurrentDevice() );

			apiResponsiveControl._dimensionSameChange( $('.dimension-width', model.container), model, values );
			apiResponsiveControl._dropdownSameChange( $('.dimension-unit', model.container), values, 'unit' );
			apiResponsiveControl._hideComponentSameChange( $('.same', model.container), model, values );
			apiResponsiveControl._autoSameChange( $('.auto-prop', model.container), model, values );
		},

		controlLogo( event, model, currentData ) {
			var values = themifyParseJSON( currentData, model.getCurrentDevice() ),
				defaultMode = themifyParseJSON( currentData, 'desktop' ).mode;

			apiResponsiveControl._colorChange( model, values );
			apiResponsiveControl._logoMode( model, values, defaultMode );
		},

		controlWidth( event, model, currentData ) {
			var values = themifyParseJSON( currentData, model.getCurrentDevice() ), context;

			context = typeof model.params.label !== 'undefined'
				? $( '[data-customize-setting-link="' + model.id.slice( 0, -5 ) + '"]', model.container ).parent()
				: model.container;

			apiResponsiveControl._dimensionChange( $('.dimension-width', context), model, values );
			apiResponsiveControl._dropdownChange( $('.dimension-unit', context), values, 'unit' );
			apiResponsiveControl._autoChange( $('.auto-prop', context), model, values );
		},

		_colorChange( model, values ) {
			var $color = $('#' + model.id + '_color_picker', model.container),
				val = values.color || '';
			$color.tfminicolors('value', val);
			$color.tfminicolors('opacity', values.opacity || '');
			if ( _.isEmpty( val ) ) {
				$color.closest('.color-picker').find('.remove-color').hide();
			} else {
				$color.closest('.color-picker').find('.remove-color').show(); 
			}
		},

		_borderColorChange( model, values ) {
			var $colors = $('.color-select', model.container ),
				$color_top = $('.color-select[data-side="top"]', model.container),
				$same = $('.same', model.container);

			if ( $same.prop('checked') ) {

				if ( $color_top.val().replace('#','') === values.color && $same.prop('checked') && model.isResponsiveStyling() ) {
					if ( _.isUndefined( model.value[model.id][model.getCurrentDevice()] ) )
						model.value[model.id][model.getCurrentDevice()] = {};

					model.value[model.id][model.getCurrentDevice()].color = values.color;
					model.value[model.id][model.getCurrentDevice()].opacity = values.opacity;
					model.setting.set(JSON.stringify( model.value[model.id] ) );
				}

				$color_top.tfminicolors('value', values.color || '' );
				$color_top.tfminicolors('opacity', values.opacity || '' );
			} else {
				$colors.each(function(){
					var side = $(this).data('side');
					if ( _.isUndefined( values[side] ) ) 
						values[side] = {};

					if ( 'top' == side && _.isEmpty( values[side].color ) ) {
						values[side].color = values.color;
						values[side].opacity = values.opacity;
					}

					$('.color-select[data-side="'+ side +'"]', model.container).tfminicolors('value', values[side].color || '' );
					$('.color-select[data-side="'+ side +'"]', model.container).tfminicolors('opacity', values[side].opacity || '' );

					if ( _.isEmpty( values[side].color ) ) {
						$(this).closest('.color-picker').find('.remove-color').hide();
					}
				});
			}
		},

		_fontStyleChange( model, values ) {
			var $fontStyle = $('.themify_font_style', model.container);
			$fontStyle.find('.button').each(function(){
				if ( values[ $(this).data('style')] && ! _.isEmpty( values[ $(this).data('style') ] ) ) {
					$(this).addClass('selected');
				} else {
					$(this).removeClass('selected');
				}
			});
		},

		_textTransformChange( model, values ) {
			var $texttransform = $('.themify_text_transform', model.container);
			if ( values.texttransform ) {
				$texttransform.find('.button[data-texttransform="'+ values.texttransform +'"]').addClass('selected').siblings().removeClass('selected');
			} else {
				$texttransform.find('.button').removeClass('selected');
			}
		},

		_textAlign( model, values ) {
			var $textAlign = $('.themify_font_align', model.container);
			if ( values.align ) {
				$textAlign.find('.button[data-align="'+ values.align +'"]').addClass('selected').siblings().removeClass('selected');
			} else {
				$textAlign.find('.button').removeClass('selected');
			}
		},

		_dropdownChange( $selector, values, key ) {
			var selected = values[ key ] && ! _.isEmpty( values[ key ] ) ? values[ key ] : '',
				$element = $selector.find('option[value="' + selected + '"]');

			if ( $element.length ) {
				$element.prop( 'selected', true );
			} else {
				$selector.find('option').prop( 'selected', false );
			}

			$selector.trigger( 'change' );
		},

		_dropdownSameChange( $selector, values, key ) {
			$selector.each(function(){
				var side = $(this).data('side'),
					selected = values[side][ key ] && ! _.isEmpty( values[side][ key ] ) ? values[side][ key ] : '',
				$element = $(this).find('option[value="'+ selected +'"]');

				if ( $element.length ) {
					$element.prop('selected', true);
				} else {
					$(this).find('option').prop('selected', false);
				}
			});
		},

		_inputChange( $selector, values, key ) {
			var val = values[ key ] && ! _.isEmpty( values[ key ] ) ? values[ key ] : '';
			$selector.val( val );
		},

		_fontFamilyChange( $selector, values ) {
			$selector.trigger('focus');
			if ( values.family && ! _.isEmpty( values.family ) ) {
				$selector.find('option[data-value="'+ values.family.name +'"]').prop('selected', true).trigger('change');
				$selector.data('selected', values.family.name);
			} else {
				$selector.find('option').first().prop('selected', true).trigger('change');
				$selector.data('selected', '');
			}
		},

		_hideComponentSameChange( $selector, model, values ) {
			var $components = $('.component', model.container),
				$rowLabel = $('.dimension-row-label:not(.same-label)', model.container),
				$sameLabel = $selector.parent().parent().find('.same-label');

			if ( ( values.same && 'same' == values.same ) || '' !== values.same ) {
				$selector.prop('checked', true);
				$components.hide();
				$rowLabel.hide();
				$sameLabel.text($sameLabel.data('same'));
			} else {
				$selector.prop('checked', false);
				$components.show();
				$rowLabel.show();
				$sameLabel.text($sameLabel.data('notsame'));
			}
		},

		_dropdownBorderSameChange( $selector, model, values ) {
			var $same = $('.same', model.container);
			$selector.each( function() {
				var side = $(this).data('side');

				if ( 'top' == side && _.isEmpty( values[side].style ) ) {
					values[side].style = values.style;
				}

				if ( values[side].style && ! _.isEmpty( values[side].style ) ) {

					if ( $(this).val() === values[side].style && $same.prop('checked') && 'top' === side && model.isResponsiveStyling() ) {
						if ( _.isUndefined( model.value[model.id][model.getCurrentDevice()] ) )
							model.value[model.id][model.getCurrentDevice()] = {};

						model.value[model.id][model.getCurrentDevice()].style = values[side].style;
						model.value[model.id][model.getCurrentDevice()].same = 'same';
						model.setting.set(JSON.stringify( model.value[model.id] ) );
					}
					$(this).val( values[side].style );
				} else {
					$(this).find('option').prop('selected', false);
				}
			});
		},

		_dimensionChange( $selector, model, values ) {
			$selector.each( function() {
				var modelVal = model.value[model.id],
					device = model.getCurrentDevice();

				if ( model.isResponsiveStyling() ) {
					_.isUndefined( modelVal[device] ) && ( modelVal[device] = {} );
					modelVal[device].width = values.width;
					model.setting.set( JSON.stringify( modelVal ) );
				}

				$( this ).val( values.width );
			});
		},

		_dimensionSameChange( $selector, model, values ) {
			var $same = $('.same', model.container);
			$selector.each(function(){
				var side = $(this).data('side');
				if ( _.isUndefined(values[side]) ) values[side] = {};
				if ( 'top' === side ) values[side].width = values.width;

				if ( $(this).val() === values[side].width && $same.prop('checked') && 'top' === side && model.isResponsiveStyling() ) {
					if ( _.isUndefined( model.value[model.id][model.getCurrentDevice()] ) )
						model.value[model.id][model.getCurrentDevice()] = {};

					model.value[model.id][model.getCurrentDevice()].width = values[side].width;
					model.setting.set(JSON.stringify( model.value[model.id] ) );
				}

				$(this).val( values[side].width );
			});
		},

		_autoChange( $selectors, model, values ) {
			$selectors.each(function(){
				var hide = $(this).data( 'hide' );

				$( this ).prop( 'checked', 'auto' === values.auto );
				$( '.' + hide, model.container ).toggleClass( 'hide-horizontally', 'auto' === values.auto );
			});
		},

		_autoSameChange( $selectors, model, values ) {
			$selectors.each(function(){
				var side = $(this).data('side'),
					hide = $(this).data('hide');
				if ( _.isUndefined(values[side]) ) values[side] = {};
				if ( 'top' === side ) values[side].auto = values.auto;

				if ( 'auto' === values[side].auto ) {
					$(this).prop('checked', true);
					$('.' + hide, model.container).addClass('hide-horizontally');
				} else {
					$(this).prop('checked', false);
					$('.' + hide, model.container).removeClass('hide-horizontally');
				}
			});
		},

		_logoMode( model, values, mode ) {
			var $logoMode = $('.logo-modes .logo-mode', model.container),
				val = values.mode || '',
				$logoTab = $logoMode.closest( '.customize-control' ),
				deskValue = mode;

			if ( model.isResponsiveStyling() ) {
				$('.remove-image, .open-media', model.container).hide();
				deskValue = $logoTab.data( 'deskValue' ) || deskValue;
			} else {
				$('.remove-image, .open-media', model.container).show();
				deskValue = val;
				$logoTab.data( 'deskValue', val );
			}

			if (deskValue == 'image') {
				var width = values.imgwidth || '',
					height = values.imgheight || '';
				$logoTab.find('.img-width').val(width);
				$logoTab.find('.img-height').val(height);
			}

			$logoMode.each( function() {
				var $el = $( this ),
					isActive = $el.val() == deskValue;
				$el.prop( 'checked', isActive );
				isActive && $el.trigger( 'click' );
			} );
			
		}
	};

	// Setup general variables
	var api = wp.customize,
		parent_api = parent.wp.customize,
			$body = $('body');

	api('header_textcolor', function (value) {
		value.bind(function (newval) {
			$('#header a, .site-title a, .site-description').css('color', newval);
		});
	});

	api('link_color', function (value) {
		value.bind(function (newval) {
			$('a').css('color', newval);
		});
	});

	api('text_color', function (value) {
		value.bind(function (newval) {
			$body.css('color', newval);
		});
	});

	// If the themifyCustomizer object is not defined, exit
	if (!themifyCustomizer) {
		return;
	}

	function getStyleId($selector) {
		return $.trim($selector).replace(/[^a-zA-Z0-9]/ig, '');
	}

	function setStyles($key, $selector, $styles) {
		var media = '',
			device = parent.wp.customize.previewedDevice.get();

		if ( 'desktop' !== device ) {
			media = 'screen and (max-width: '+ themifyCustomizer.breakpoints[ device ] +'px)';
		}

		var rule = get_css_rule( $selector, media );
		if ( ! _.isUndefined( rule ) ) {
			for (var st in $styles) {
				
				if ($styles[st]) {
					if(st.indexOf('--')===0){
						rule.style.setProperty(st,$styles[st]);
					}else{
						rule.style[ st ] = $styles[st];
					}
				} else {
					if(st.indexOf('--')===0){
						rule.style.removeProperty(st);
					}else{
						rule.style[ st ] = '';
					}
				}
			}
		} else {
			var $inline = '';
			for (var st in $styles) {
				if ($styles[st]) {
					$inline += st + ':' + $styles[st] + ';';
				}
			}
			var sheet = get_css_sheet(),
				newRule = $selector + '{'+ $inline +'}',
				length = Math.max( sheet.cssRules.length - 3, 0 );

			if ( '' !== media ) {
				var new_sheet = get_css_sheet( media );
				if ( _.isUndefined( new_sheet ) ) {
					newRule = '@media ' + media + ' { '+ newRule +' }';
					var bp_values = _.values( themifyCustomizer.breakpoints );
					length = sheet.cssRules.length;

					// desktop, tablet_landscape, tablet, mobile
					if ( sheet.cssRules.length && sheet.cssRules[ sheet.cssRules.length - 1 ].media ) {
						
						if ( 'tablet_landscape' === device ) {
							var check_tablet = get_css_index('screen and (max-width: '+ bp_values[1] +'px)');
							if ( ! _.isUndefined( check_tablet ) ) {
								length = check_tablet;
							} else {
								var check_mobile = get_css_index('screen and (max-width: '+ bp_values[2] +'px)');
								if ( ! _.isUndefined( check_mobile ) ) 
									length = check_mobile;
							}
						}

						if ( 'tablet' === device ) {
							var check_tablet_ls = get_css_index('screen and (max-width: '+ bp_values[0] +'px)');
							if ( ! _.isUndefined( check_tablet_ls ) ) {
								length = check_tablet_ls + 1;
							} else {
								var check_mobile = get_css_index('screen and (max-width: '+ bp_values[2] +'px)');
								if ( ! _.isUndefined( check_mobile ) ) 
									length = check_mobile;
							}
						}
					}

				} else {
					sheet = new_sheet;
					length = new_sheet.cssRules.length;
				}
			}
			sheet.insertRule( newRule, length );
		}

	}

	function get_css_sheet( media ) {
		media = media || '';
		var mysheet= $('#themify-customize').get(0).sheet;

		if ( '' === media ) return mysheet;

		var myrules = mysheet.cssRules? mysheet.cssRules: mysheet.rules, targetrule;

		if ( '' !== media ) {
			for (var i=0; i< myrules.length; i++){
				if ( myrules[i].media && myrules[i].cssText.indexOf(media) > -1 ) {
					targetrule = myrules[i];
					break;
				}
			}
			return targetrule;
		}
	}

	function get_css_index( media ) {
		media = media || '';
		var mysheet= $('#themify-customize').get(0).sheet;

		if ( '' === media ) return mysheet;

		var myrules = mysheet.cssRules? mysheet.cssRules: mysheet.rules, targetrule;

		if ( '' !== media ) {
			for (var i=0; i< myrules.length; i++){
				if ( myrules[i].media && myrules[i].cssText.indexOf(media) > -1 ) {
					targetrule = i;
					break;
				}
			}
			return targetrule;
		}
	}

	function get_css_rule( searchrule, media ) {
		media = media || '';
		searchrule = searchrule.replace(/,/g, ', '); // To match with stylesheet rules
		if ( $('#themify-customize').length == 0 ) {
			$('body').append('<style id="themify-customize"></style>'); // create empty stylesheet
		}

		var mysheet= $('#themify-customize').get(0).sheet,
			myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules,
			targetrule;

		if ( '' === media ) {
			for (var i=0; i<myrules.length; i++){
				if( ! _.isUndefined( myrules[i].selectorText ) && myrules[i].selectorText.toLowerCase() == searchrule ){
					targetrule = myrules[i]
					break;
				}
			}
		} else {
			for (var i=0; i<myrules.length; i++){
				if ( myrules[i].media && myrules[i].cssText.indexOf(media) > -1 ) {
					var mediaRules = myrules[i].cssRules ? myrules[i].cssRules : myrules[i].rules;
					for (var ii = 0; ii < mediaRules.length; ii++) {
						if ( ! _.isUndefined( mediaRules[ii].selectorText ) && mediaRules[ii].selectorText.toLowerCase() == searchrule ) {
							targetrule = mediaRules[ii];
							break;
						}
					};
					break;
				}
			}
		}
		return targetrule;
	}

	function responsive_trigger_event( controls, key ) {
		if (controls) {
			$.each(controls, function (index, selector) {
				var model = parent_api.control.instance( index + '_ctrl');

				if ( ! _.isEmpty( model.setting.get() ) ) {
					var currentData = model.setting.get();
					$.event.trigger( key, [ model, currentData ]);
				}
			});
		}
	}
	$(document).on('themify.customizer', function (e, $id, $selector) {
		var $key = 'themify-customizer-css-' + $id;
		if ($('#' + $key).length > 0) {
			$('#' + $key).remove();
		}
		setStyles($key, $selector, styles[$id]);
		if ($id === 'sitelogo' && typeof styles[$id]['color'] !== 'undefined') {
			var $color = styles[$id]['color'];
			$id = $id + 'a';
			if (!styles[$id]) {
				styles[$id] = [];
			}
			styles[$id]['color'] = $color;
			$.event.trigger("themify.customizer", [$id, '#site-logo a']);
		}

	});

	parent_api.previewedDevice.bind( 'change', function( device ) {
		responsive_trigger_event( themifyCustomizer.backgroundControls, 'themify-responsive-preview-background' );
		responsive_trigger_event( themifyCustomizer.colorControls, 'themify-responsive-preview-color-control' );
		responsive_trigger_event( themifyCustomizer.fontControls, 'themify-responsive-preview-fonts-control' );
		responsive_trigger_event( themifyCustomizer.borderControls, 'themify-responsive-preview-border-control' );
		responsive_trigger_event( themifyCustomizer.marginControls, 'themify-responsive-preview-margin-control' );
		responsive_trigger_event( themifyCustomizer.paddingControls, 'themify-responsive-preview-padding-control' );
		responsive_trigger_event( themifyCustomizer.logoControls, 'themify-responsive-preview-logo-control' );
		responsive_trigger_event( themifyCustomizer.widthControls, 'themify-responsive-preview-width-control' );
	} );
	
	// Remove stylesheets when clearAll
	$( window ).on( 'message', function( event ) {
		if ( event.originalEvent && event.originalEvent.data && ! _.isEmpty( event.originalEvent.data ) ) {
			try {
				var data = $.parseJSON( event.originalEvent.data ) || {};
			}
			catch( error ) {
				var data = {};
			}
			if ( 'themify-customize-clearall' === data.id ) {
				styles = [];
				$('#themify-customize').remove(); // remove the css
			}
		}
	} );

	// Setup font family, styles, size and eveything
	function setFont($id, font) {
		var $sides = ['font-family', 'font-weight', 'font-size', 'font-style', 'text-transform', 'text-decoration', 'text-align', 'line-height'];
		if (!styles[$id]) {
			styles[$id] = [];
		}
		_.each($sides, function (side) {
			styles[$id][side] = false;
		});

		if (font) {
			if (font.family) {
				if (font.family.fonttype && ( 'google' === font.family.fonttype || 'cf' === font.family.fonttype )) {
					var $font = font.family.name;
					if(font.weight && font.weight!=='normal'){
					   $font+=':normal,'+font.weight;
					}
					if($('link[href*="'+$font.replace(/ /g, '+')+'"]').length===0){
						var webFontConfig = {};
						if('google' === font.family.fonttype){
							webFontConfig['google'] = {families: [$font]};
						}else{
							webFontConfig['custom'] = {families: [$font],urls:[themifyCustomizer.cf_api_url+$font]};
						}
						WebFont.load(webFontConfig);
					}
				}
				styles[$id]['font-family'] = font.family.name;
			}

			if (!font.nostyle) {
				if (font.bold) {
					styles[$id]['font-weight'] = 'bold';
				}

				if (font.italic) {
					styles[$id]['font-style'] = 'italic';
				}
				else if (font.normal) {
					styles[$id]['font-style'] = 'normal';
				}

				if (font.linethrough) {
					styles[$id]['text-decoration'] = 'line-through';
				}
				else if (font.underline) {
					styles[$id]['text-decoration'] = 'underline';


				} else {
					styles[$id]['font-weight'] = styles[$id]['font-style'] = 'normal';
					styles[$id]['text-decoration'] = 'none';
				}

				if (!font.normal) {
					if (font.bold) {
						styles[$id]['font-weight'] = 'bold';
					}

					if (font.italic) {
						styles[$id]['font-style'] = 'italic';
					}

				} else {
					styles[$id]['font-style'] = 'normal';
				}
			}
			if (font.texttransform) {
				styles[$id]['text-transform'] = 'notexttransform' !== font.texttransform ? font.texttransform : 'none';
			}

			if (font.align) {
				styles[$id]['text-align'] = 'noalign' !== font.align ? font.align : false;
			}
			if (font.sizenum > 0) {
				styles[$id]['font-size'] = font.sizenum + (font.sizeunit ? font.sizeunit : 'px');
			}
			if (font.letterspacing) {
				styles[$id]['letter-spacing'] = font.letterspacing + (font.letterspacingunit ? font.letterspacingunit : 'px');
			}
			if (font.linenum > 0) {
				styles[$id]['line-height'] = font.linenum + (font.lineunit ? font.lineunit : 'px');
			}
			if (font.weight) {
				styles[$id]['font-weight'] = font.weight;
			}
			else if(!font.bold){
				 styles[$id]['font-weight'] = false;
			}
		}
	}

	////////////////////////////////////////////////////////////////////////////
	// Font Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.fontControls) {
		$.each(themifyCustomizer.fontControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (fontData) {
					var values = themifyParseJSON(fontData),
							$id = getStyleId(selector);
					setFont($id, values);
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Font Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Logo Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.logoControls) {
		$.each(themifyCustomizer.logoControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (imageData) {
					var values = themifyParseJSON(imageData),
							$selector = $(selector),
							$id = getStyleId(selector);
					if (!styles[$id]) {
						styles[$id] = [];
					}
					setFont($id, values);
					if (values.mode && 'none' === values.mode) {
						styles[$id]['display'] = 'none';
					} else {
						styles[$id]['display'] = 'block';

						var $img = $('img:not(.tf_sticky_logo)', $selector);
						if ( $img.length > 0 ) {
							$img.remove();
						}

						if (values.mode && 'image' === values.mode) {
							$selector.find('span').hide();
							if ('undefined' !== typeof values.src && values.src) {
								if ($('a', $selector).length > 0) {
									$selector.find('a').append('<img src="' + values.src + '" />');
									if (values.link) {
										$selector.find('a').attr('href', values.link);
									}
								} else {
									$selector.append('<img src="' + values.src + '" />');
								}
							}
							var imgwidth = values.imgwidth ? values.imgwidth : '',
								imgheight = values.imgheight ? values.imgheight : '';
							$selector.find('img:not(.tf_sticky_logo)').css({
								'width': imgwidth,
								'height': imgheight
							});
						} else {
							$selector.find('span').show();
							if ($selector.length > 0) {
								if (values.link) {
									$selector.find('a').attr('href', values.link);
								}
								styles[$id]['color'] = getColor(values);
							}

							$.post(
									themifyCustomizer.ajaxurl,
									{
										'action': 'themify_customizer_get_option',
										'option': 'blogname',
										'nonce': themifyCustomizer.nonce
									},
							function (data) {
								if ('notfound' !== data) {
									$('#site-logo, #footer-logo').find('span').text(data);
								}
							}
							);
						}
					}
					$.event.trigger("themify.customizer", [$id, selector]);

				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Logo Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Tagline Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.taglineControls) {
		$.each(themifyCustomizer.taglineControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (imageData) {
					var values = $.parseJSON(imageData),
							$selector = $(selector),
							$id = getStyleId(selector);
					if (!styles[$id]) {
						styles[$id] = [];
					}
					setFont($id, values);
					if (values.mode && 'none' === values.mode) {

						styles[$id]['display'] = 'none';

					} else if ('none' !== values.mode) {

						styles[$id]['display'] = 'block';
						var $img = $('img', $selector);
						if ($img.length > 0) {
							$img.remove();
						}
						if (values.mode && 'image' === values.mode) {
							$selector.find('span').hide();
							if ('undefined' !== typeof values.src && values.src) {
								$selector.prepend('<img src="' + values.src + '" />');
								var imgwidth = values.imgwidth ? values.imgwidth : '',
										imgheight = values.imgheight ? values.imgheight : '';
								$selector.find('img').css({
									'width': imgwidth,
									'height': imgheight
								});
							}
						} else {
							$selector.find('span').show();
							styles[$id]['color'] = getColor(values);
							;
							$.post(
									themifyCustomizer.ajaxurl,
									{
										'action': 'themify_customizer_get_option',
										'option': 'blogdescription',
										'nonce': themifyCustomizer.nonce
									},
							function (data) {
								if ('notfound' != data) {
									$selector.find('span').text(data);
								}
							}
							);
						}
					}
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Tagline Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Background Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.backgroundControls) {
		$.each(themifyCustomizer.backgroundControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (backgroundData) {
					var values = themifyParseJSON(backgroundData),
							$id = getStyleId(selector),
							$sides = ['image', 'color', 'repeat', 'size', 'position'];
					if (!styles[$id]) {
						styles[$id] = [];
					}
					_.each($sides, function (side) {
						styles[$id]['background-' + side] = false;
					});

					if (values && 'noimage' !== values.noimage && 'undefined' !== typeof values.src) {
						styles[$id]['background-image'] = 'url(' + values.src + ')';
					}
					if ('undefined' !== typeof values.style && values.style) {

						if ('fullcover' === values.style) {
							styles[$id]['background-size'] = 'cover';
							styles[$id]['background-repeat'] = 'no-repeat';
						} else {
							styles[$id]['background-size'] = 'auto';
							styles[$id]['background-repeat'] = values.style;
						}
					}
					if ('undefined' !== typeof values.position && values.position) {
						styles[$id]['background-position'] = values.position;
					}

					if ( values.transparent ) {
						styles[$id]['background-color'] = 'transparent';
					} else {
						styles[$id]['background-color'] = getColor(values);
					}
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Background Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Color Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.colorControls) {
		$.each(themifyCustomizer.colorControls, function (index, selector) {
			let prop='color';
			if('object'===typeof selector){
				prop=selector.v;
				selector=selector.id;
			}
			api(index, function (value) {
				value.bind(function (colorData) {
					var values = themifyParseJSON(colorData),
							$id = getStyleId(selector);
					if (!styles[$id]) {
						styles[$id] = [];
					}
					styles[$id][prop] = getColor(values);
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	if (themifyCustomizer.borderColorControls) {
		$.each(themifyCustomizer.borderColorControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (colorData) {
					var values = themifyParseJSON(colorData),
							$id = getStyleId(selector);
					if (!styles[$id]) {
						styles[$id] = [];
					}
					styles[$id]['border-color'] = getColor(values);
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Color Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Image Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.imageselectControls) {
		$.each(themifyCustomizer.imageselectControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (imageData) {
					var values = $.parseJSON(imageData);
					if (values) {
						var $img = $( '.tf_sticky_logo' );
						if ( $img.length > 0 ) {
							$img.remove();
						}
						if (values.src) {
							var img = '<img class="tf_sticky_logo" src="' + values.src + '"';
							var style = '';
							if(values.imgwidth){
								img+=' width="'+values.imgwidth+'"';
								style += 'width: ' + values.imgwidth + 'px;';
							}
							if(values.imgheight){
								img+=' height="'+values.imgheight+'"';
								style += 'height: ' + values.imgheight + 'px;';
							}
							img += ' style="' + style + '" />';
							$( '#headerwrap #site-logo a' ).prepend( img );
						}
					}
				});
			});
		});
	}

	////////////////////////////////////////////////////////////////////////////
	// Image Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Border Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.borderControls) {
		$.each(themifyCustomizer.borderControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (borderData) {
					var values = themifyParseJSON(borderData),
							$id = getStyleId(selector),
							$sides = ['border', 'border-color', 'border-top', 'border-left', 'border-bottom', 'border-right', 'border-width', 'border-style'];
					if (!styles[$id]) {
						styles[$id] = [];
					}
					_.each($sides, function (side) {
						delete styles[$id][side];
					});

					if (values && 'disabled' !== values.disabled) {
						if ('same' !== values.same) {
							_.each(['top', 'left', 'bottom', 'right'], function (side) {
								if (values[side]) {
									if ( 'top' === side ) {
										_.extend( values[ side ], _.pick( values, _.keys( values[side] ) ) );
									}
									styles[$id]['border-' + side] = getBorder(values[side]);
								}
							});
						} else {
							styles[$id]['border'] = getBorder(values);
						}
					}
					
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Border Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Margin Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.marginControls) {
		$.each(themifyCustomizer.marginControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (marginData) {
					var values = themifyParseJSON(marginData),
							$id = getStyleId(selector),
							$sides = ['margin', 'margin-top', 'margin-left', 'margin-bottom', 'margin-right'];
					if (!styles[$id]) {
						styles[$id] = [];
					}
					_.each($sides, function (side) {
						delete styles[$id][side];
					});
					if (values && 'disabled' !== values.disabled) {
						if ('same' !== values.same) {
							_.each(['top', 'left', 'bottom', 'right'], function (side) {
								if (values[side]) {
									if ( 'top' === side ) {
										_.extend( values[ side ], _.pick( values, _.keys( values[side] ) ) );
									}
									styles[$id]['margin-' + side] = getDimension(values[side]);
								}
							});
						} else {
							styles[$id]['margin'] = getDimension(values);
						}
					}
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Margin Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Padding Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.paddingControls) {
		$.each(themifyCustomizer.paddingControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (paddingData) {
					var values = themifyParseJSON(paddingData),
							$id = getStyleId(selector),
							$sides = ['padding', 'padding-top', 'padding-left', 'padding-bottom', 'padding-right'];
					if (!styles[$id]) {
						styles[$id] = [];
					}
					_.each($sides, function (side) {
						delete styles[$id][side];
					});
					if (values && 'disabled' !== values.disabled) {
						if ('same' !== values.same) {
							_.each(['top', 'left', 'bottom', 'right'], function (side) {
								if (values[side]) {
									if ( 'top' === side ) {
										_.extend( values[ side ], _.pick( values, _.keys( values[side] ) ) );
									}
									styles[$id]['padding-' + side] = getDimension(values[side]);
								}
							});
						} else {
							styles[$id]['padding'] = getDimension(values);
						}
					}
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Padding Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Width Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.widthControls) {
		$.each(themifyCustomizer.widthControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (widthData) {
					var values = themifyParseJSON( widthData ),
						$id = getStyleId(selector);

					if (!styles[$id]) {
						styles[$id] = [];
					}
					styles[$id]['width'] = getDimension(values);
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Width Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Height Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.heightControls) {
		$.each(themifyCustomizer.heightControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (heightData) {
					var values = $.parseJSON(heightData),
							$id = getStyleId(selector);
					if (!styles[$id]) {
						styles[$id] = [];
					}
					styles[$id]['height'] = getDimension(values);
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Height Control End
	////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////
	// Position Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.positionControls) {
		$.each(themifyCustomizer.positionControls, function (index, selector) {
			api(index, function (value) {
				value.bind(function (positionData) {
					var values = $.parseJSON(positionData),
							$id = getStyleId(selector),
							$sides = ['position', 'top', 'left', 'bottom', 'right'];
					if (!styles[$id]) {
						styles[$id] = [];
					}
					_.each($sides, function (side) {
						styles[$id][side] = false;
					});
					if (values && values.position) {
						styles[$id]['position'] = values.position;
						_.each(['top', 'right', 'bottom', 'left'], function (side) {
							if (values[side]) {
								styles[$id][side] = getDimension(values[side]);
							}
						});
					}
					$.event.trigger("themify.customizer", [$id, selector]);
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Position Control End
	////////////////////////////////////////////////////////////////////////////


	////////////////////////////////////////////////////////////////////////////
	// Custom CSS Control Start
	////////////////////////////////////////////////////////////////////////////
	if (themifyCustomizer.customcssControls) {
		var initialLoad = [];
		$.each(themifyCustomizer.customcssControls, function (index, selector) {
			initialLoad[index] = true;
			api(index, function (value) {
				value.bind(function (customcssData) {
					var stylesheet = 'themify-customize-customcss',
							$stylesheet = $('#' + stylesheet);
					if ($stylesheet.length > 0) {
						$stylesheet.remove();
					}
					if (customcssData) {
						customcssData = customcssData
								.replace(/[\n]/g, '')
								.replace(/[\r]/g, '')
								.replace(/[\t]/g, '')
						$('head').append('<style type="text/css" id="' + stylesheet + '">' + customcssData + '</style>');
					}
				});
			});
		});
	}
	////////////////////////////////////////////////////////////////////////////
	// Custom CSS Control End
	////////////////////////////////////////////////////////////////////////////

	apiResponsiveControl.init(); // initialize api responsive control

})(jQuery);
