/**
 * jQuery assets for handling the WpFonts 
 * chained events, specially for helping user
 * on selecting the right options for google
 * fonts.
 * 
 * @author jason.xie@victheme.com
 */
(function($) {

  $(document)
    
    // Initialize first time
    .on('ready', function() {
      $('.wp-fonts [data-font="family"]').trigger('change');
    })
    
    
    // Bind on change events
    .off('change', '.wp-fonts [data-font="family"]')
    .on('change', '.wp-fonts [data-font="family"]', function() {
      
      // Build simple object
      var fontObject = {
            parent : $(this).closest('.wp-fonts'),
            value : $(this).val(),
            option : $(this).find('[value="' + $(this).val() + '"]'),
            tweight : $(this).closest('.wp-fonts').find('[data-font="weight"]'),
            tstyle : $(this).closest('.wp-fonts').find('[data-font="style"]'),
            weight : [], 
            style : []
          };
      
      // Reset weight
      fontObject
        .tweight
        .find('option')
        .removeAttr('disabled')
        .show();
      
      // Reset style
      fontObject
        .tstyle
        .find('option')
        .removeAttr('disabled')
        .show();
      
      // Only proceed if we got valid variants
      if (fontObject.option.data('variants')) {
        
        // Loop and process the variants
        $.each(fontObject.option.data('variants'), function(key, val) {
          
          // Change regular to valid weight
          if (val == 'regular') {
            val = '400';
          }
          
          // Catch italic, in the future if google fonts
          // support more style add the logic here.
          if (val.indexOf('italic') != -1) {
            fontObject.style.push('[value="italic"]');
            val.replace('italic', '');
          }
          
          // Store all catched logic
          fontObject.weight.push('[value="' + val + '"]');
        });
        
        // Disable and hide not supported google fonts weight
        if (fontObject.weight.length) {
          fontObject.weight.push('[value=""]');
          fontObject
            .tweight
            .find('option:not(' + fontObject.weight.join(', ') + ')')
            .attr('disabled', true)
            .hide();
          fontObject
            .tweight
            .val('')
            .find('option')
            .removeAttr('selected');
        }
        
        // Disable and hide not supported google fonts style
        if (fontObject.style.length) {
          fontObject.style.push('[value=""]');
          fontObject
            .tstyle
            .find('option:not(' + fontObject.style.join(', ') + ')')
            .attr('disabled', true)
            .hide();  
          fontObject
            .tstyle
            .val('')
            .find('option')
            .removeAttr('selected');
        }
      }
      
      // Free up object
      delete fontObject;
    });
  

})(jQuery);