/**
 * Live preview js for customizer.
 * 
 * This js script must be loaded via hook
 * customizer_preview_init action or
 * it wont work!.
 * 
 * The assets dependencies are :
 * 1. jquery-deparam 
 * 2. wp-gradientpicker
 * 
 * must be loaded first before this script
 * to avoid missing function error.
 * 
 * @author jason.xie@victheme.com
 * @see VTCore_Wordpress_Customizer_Element_Grid
 * @see VTCore_Wordpress_Customizer_Element_Hidden
 * @see VTCore_Wordpress_Customizer_Element_Gradient
 * @see VTCore_Wordpress_Form_WpGradient
 * @see VTCore_Zeus_Customizer_Factory
 * @see VTCore_Zeus_Schema_Color
 */
(function($) {

  $.each(window.parent.wp.customize.settings.settings, function(key, val) {

    // Force Refresh loaded schema when user change schema
    if (key == 'schema-active') {

      window.parent.wp.customize(key, function(value) {
        value.bind(function (newval) {

          var url = window.ajaxurl || window.parent.wp.ajax.settings.url;

          // Refresh schema
          $.ajax({
            url: url,
            type: 'POST',
            cache: false,
            data: {
              action: 'color_customizer',
              colorSelects: newval
            },
            dataType: 'json',
            /**
             beforeSend: function (arr, $form, options) {
              //NoticeBox.fadeIn();
            },
             complete: function (arr, $form, options) {
              //NoticeBox.fadeOut();
            },
             **/
            success: function (response, status) {

              $.each(response, function (parent, arrays) {
                var key = 'schemas[color][' + parent + ']';
                $.each(arrays, function (child, newColor) {

                  if (child != 'selectors' && child != 'title' && child != 'description') {
                    var control = window.parent.wp.customize.control.instance(key + '[' + child + ']');

                    if (typeof control != 'undefined'
                        && typeof control.setting != 'undefined') {

                      control.setting.set(newColor);

                      // Update the color picker
                      if (typeof control.container != 'undefined'
                          && typeof control.container.children().data('colorpicker') != 'undefined') {
                        control.container.children().data('colorpicker').setValue(newColor);
                      }

                    }

                  }
                });
              });

            }
          });

        });
      });
    }


    // Processing grids
    if (key.indexOf('regions[') != -1) {

      window.parent.wp.customize(key, function(value) {

        // process key
        var eMatch = false,
            cssMode = false,
            eMode = false,
            eSize = false;

        eMatch = key.replace('regions[', '').replace(/\]\[/g, '.').replace(']', '').split('.').reverse();

        if (eMatch != null) {
          eSize = eMatch[0];
          eMode = eMatch[1];
        }

        // Detect Bootstrap first prefix
        if (eMode == 'columns'
            || eMode == 'push'
            || eMode == 'pull'
            || eMode == 'offset') {
          cssMode = 'col-';
        }

        else if (eMode == 'hidden') {
          cssMode = 'hidden-';
        }
        else if (eMode == 'visible') {
          cssMode = 'visible-';
        }

        // Detect Bootstrap second prefix
        if (eSize == 'mobile') {
          cssMode += 'xs-';
        }

        else if (eSize == 'tablet') {
          cssMode += 'sm-';
        }

        else if (eSize == 'small') {
          cssMode += 'md-';
        }
        else if (eSize == 'large') {
          cssMode += 'lg-';
        }

        // Detect bootstrap last prefix
        if (eMode == 'push') {
          cssMode += 'push-';
        }

        else if (eMode == 'pull') {
          cssMode += 'pull-'
        }

        else if (eMode == 'offset') {
          cssMode += 'offset-';
        }

        // Bind only if valid bootstrap prefix made
        if (cssMode && typeof window.parent.wp.customize.settings.controls[key] != 'undefined') {

          var pointer = window.parent.wp.customize.settings.controls[key]['pointer'];

          value.bind(function (newval) {

            // Find and remove old bootstrap css
            // class. only target the same prefix.
            var classes = $(pointer.target).attr('class').split(' ');

            $.each(classes, function(delta, stringClass) {
              if (stringClass.indexOf(cssMode) != -1) {
                $(pointer.target).removeClass(stringClass);
              }
            });

            // Add the new bootstrap prefix plus size.
            $(pointer.target).addClass(cssMode + newval);

            // Relayout isotope
            if ($(pointer.target).parent().hasClass('js-isotope')) {
              $(pointer.target).parent().isotope('layout');
            }

          });
        }

      });


    }




    // Processing color schema items
    if (key.indexOf('schemas[color]') != -1) {
      
      var pointer = window.parent.wp.customize.settings.controls[key]['pointer'],
          type = window.parent.wp.customize.settings.controls[key]['type'];
      
      window.parent.wp.customize(key, function(value) {
        value.bind(function(newval) {

          // Convert image to css valid value
          if (pointer.rules == 'background-image') {
            newval = 'url(' + newval + ')';
          }

          // Inject google fonts
          if (pointer.rules == 'font-family' && newval.indexOf(',') == -1) {
            var id = newval.split('+').join('-');
            if ($("head").find('#vtcore-customizer-' + id).length == 0) {
              $("head").append('<link id="vtcore-customizer-' + id + '" href="http://fonts.googleapis.com/css?family=' + newval + '&subset=latin,cyrillic-ext,cyrillic,greek-ext,greek,vietnamese,latin-ext" rel="stylesheet" type="text/css">"');
            }
            
            newval = '"' + newval.split('+').join(' ') + '"';
          }
          
          // Support for gradient + WpGradient object
          if (type == 'gradient') {
           
            var query = [];
            $.each($.parseJSON(newval), function(key, object) {
              query.push(object.name.replace('[gradient]', 'gradient') + '=' + encodeURIComponent(object.value));
            });
 
            // Depends on jquery-deparam assets
            query = $.fn.deparam(query.join('&'));
            
            if (typeof query.gradient != 'undefined') {
              // Depends on wp-gradientpicker assets
              $(pointer.target).VTCoreGradient(query.gradient);
            }
          }
          // Other elements
          else {
            $(pointer.target).css(pointer.rules, newval);
          }
          
        });
        
      }); 
    }
  });

})(jQuery);
