/**
 * @file
 *   Contains JS required for less watch functionality.
 */
;(function ($) {
  "use strict";
  
  Drupal.behaviors.less_watch = {
    attach: function (context, settings) {
      
      var watched_files = [],
          $watched_links;
      
      $watched_links = $('head link[src$=".less"]', context).each(function () {
        
        // Only grab the portion of the url up to, but not including, the '?'.
        watched_files.push($(this).attr('href'));
      });
      
      if (watched_files.length > 0) {
        
        // Modeled after example @ http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/
        var poller = {
         
          failed_requests: 0,
        
          // starting interval in milliseconds
          interval: 500,
        
          // kicks off the setTimeout
          init: function(){
            setTimeout(
              $.proxy(this.getData, this), // ensures 'this' is the poller obj inside getData, not the window object
              this.interval
            );
          },
         
          // get AJAX data + respond to it
          getData: function() {
            var self = this;
       
            $.ajax({
              type: 'POST',
              url: settings.basePath + 'ajax/less/watch',
              data: {
                less_files: watched_files
              },

              // On success, reset failed request counter and update style links.
              success: function ( response ) {
                
                self.failed_requests = 0;
                
                $.each(response, function (index, value) {
                  var old_file = value.old_file,
                      new_file = value.new_file;
                  
                  // Math.random() at the end forces a reload of the file.
                  $('head link[href^="' + old_file + '"]', context).replaceWith($('<link type="text/css" rel="stylesheet" media="all" />').attr('href', new_file + '?' + Math.random()));
                  
                  watched_files[$.inArray(old_file, watched_files)] = new_file;
                });
              },
              
              // On failure, count failed request and increase interval.
              error: function () {
                
                ++self.failed_requests;
         
                self.interval += 500;
              },
              
              // On success or failure, restart
              complete: function () {
                
                if( ++self.failed_requests < 10 ){
                  self.init();
                }
              }
            });
          }
        };
         
        poller.init();
        
      }
      
    }
  };

})(jQuery);
