/***************************************************************************
 *
 * 	----------------------------------------------------------------------
 * 						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 {
            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 : '') :
                false;
    }

    function themifyParseJSON(data, device) {
        device = device || parent.wp.customize.previewedDevice.get();
        var rawJson = $.parseJSON( 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;
        }
    }

    var apiResponsiveControl = {
        init: function() {
            $(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
        },

        controlBackground: function( event, model, currentData ) {
            var $transparent = $('.color-transparent', 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,
                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');
            }

            $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: function( event, model, currentData) {
            var values = themifyParseJSON( currentData, model.getCurrentDevice() );
            apiResponsiveControl._colorChange( model, values );
        },

        controlFonts: function( 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._dropdownChange( $('.font_weight_select', model.container), values, 'weight' );
        },

        controlBorder: function( 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: function( 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 );
        },

        _colorChange: function( model, values ) {
            var $color = $('.color-select', model.container),
                val = values.color || '';
            $color.minicolors('value', val);
            $color.minicolors('opacity', val);
            if ( _.isEmpty( val ) ) {
                $color.closest('.color-picker').find('.remove-color').hide();
            } else {
                $color.closest('.color-picker').find('.remove-color').show(); 
            }
        },

        _borderColorChange: function( model, values ) {
            var $colors = $('.color-select', model.container );

            $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).minicolors('value', values[side].color || '' );
                $('.color-select[data-side="'+ side +'"]', model.container).minicolors('opacity', values[side].opacity || '' );

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

        _fontStyleChange: function( 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: function( 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: function( 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: function( $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);
            }
        },

        _dropdownSameChange: function( $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: function( $selector, values, key ) {
            var val = values[ key ] && ! _.isEmpty( values[ key ] ) ? values[ key ] : '';
            $selector.val( val );
        },

        _fontFamilyChange: function( $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: function( $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: function( $selector, model, values ) {
            $selector.each( function() {
                var side = $(this).data('side');

                if ( values[side].style && ! _.isEmpty( values[side].style ) ) {
                    $(this).find('option[value="'+ values[side].style +'"]').prop('selected', true);
                } else {
                    $(this).find('option').prop('selected', false);
                }
            });
        },

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

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

        _autoSameChange: function( $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');
                }
            });
        }
    };

    // 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]) {
                    rule.style[ st ] = $styles[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 || '';

        if ( $('#themify-customize').length == 0 ) {
            $('head').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');

        // Hide section for responsive not available
        if ( themifyCustomizer.logoControls ) {
            $.each( themifyCustomizer.logoControls, function( index, selector ) {
                var model = parent_api.control.instance( index + '_ctrl');
                if ( 'desktop' !== device ) {
                    $( model.container ).closest('.customize-control-themify_subaccordion_start').addClass('responsive-na');
                } else {
                    $( model.container ).closest('.customize-control-themify_subaccordion_start').removeClass('responsive-na');
                }
            });
        }
    });
    
    // Remove stylesheets when clearAll
    $( window ).on( 'message', function( event ) {
        if ( event.originalEvent && event.originalEvent.data && ! _.isEmpty( event.originalEvent.data ) ) {
            var data = $.parseJSON( event.originalEvent.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) {
                    WebFont.load({
                        google: {
                            families: [font.family.name]
                        }
                    });
                }
                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.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 = $.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 {
                        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) {
                                if ($('a', $selector).length > 0) {
                                    $selector.find('a').prepend('<img src="' + values.src + '" />');
                                    if (values.link) {
                                        $selector.find('a').attr('href', values.link);
                                    }
                                } else {
                                    $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();
                            if ($('a', $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;
                    }

                    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) {
            api(index, function (value) {
                value.bind(function (colorData) {
                    var values = themifyParseJSON(colorData),
                            $id = getStyleId(selector);
                    if (!styles[$id]) {
                        styles[$id] = [];
                    }
                    styles[$id]['color'] = getColor(values);
                    $.event.trigger("themify.customizer", [$id, selector]);
                });
            });
        });
    }
    ////////////////////////////////////////////////////////////////////////////
    // Color Control End
    ////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////
    // Image Control Start
    ////////////////////////////////////////////////////////////////////////////
    if (themifyCustomizer.imageControls) {
        $.each(themifyCustomizer.imageControls, function (index, selector) {
            api(index, function (value) {
                value.bind(function (imageData) {
                    var values = $.parseJSON(imageData),
                            $selector = $(selector);

                    if (values) {
                        var $img = $('img', $selector);
                        if ($img.length > 0) {
                            $img.remove();
                        }
                        if (values.src) {
                            $($selector).prepend('<img src="' + values.src + '" />');
                        }
                    }
                });
            });
        });
    }
    ////////////////////////////////////////////////////////////////////////////
    // 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 = $.parseJSON(widthData),
                            $id = getStyleId(selector);
                    if (!styles[$id]) {
                        styles[$id] = [];
                    }
                    styles[$id]['height'] = 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);