/**
 * A simple ticker plugin for jQuery
 *
 * Scrolls the children of a specified node horizontally like the ticker
 * at the bottom of most news programs.
 *
 * Example usage:
 *
 *   <ul id="myTicker">
 *     <li><a href="#">My first headline</a></li>
 *     <li><a href="#">My second headline</a></li>
 *     ...
 *     <li><a href="#">My last headline</a></li>
 *   </ul>
 *
 *   $('#myTicker').tick({
 *     distance: 1,           // Number of pixels to move with tick
 *     velocity: 15,          // Interval between ticks (in milliseconds)
 *     offset:   'right',     // Initial x-axis offset of items (in pixels)
 *     fade:     1000         // Duration of fade effect (in milliseconds)
 *   });
 *
 * @method tick
 * @version 0.9
 * @author Dave Furfero <dave.furf.tii@gmail.com>
 * @static
 * @param  {object} cfg   Optional configuration parameters (see above)
 * @return {array}        Ticker-enabled jQuery objects
 */
$.fn.tick = function(cfg) {

  return this.each(function() {

    // Ticker
    var ticker = $(this);

    // Items
    var items = ticker.children();

    // Nothing to tick?
    if (items.size() === 0) {
      return false;
    }

    // Enforce required CSS for ticker container
    ticker.css({
      position: 'relative',
      overflow: 'hidden'
    });

    var tickerEl = ticker.get(0);
    var tickerWidth = ticker.width();

	// Override default values with user-configured settings
	var config = $.extend({
	distance: 2,
	velocity: 30,
	offset: 0,
	fade: 0
	}, cfg || {});

    // Prepare fade in event
    if (config.fade > 0) {
      items.hide();
    }

    // Set the initial offset X position of ticker items
    // Acceptable values are 'left', 'right', 'center',
    // and percentages between '0%' and '100%'

    var pctRegExp = /^(-?\d+(\.\d+)?)%$/;

    if (typeof config.offset === 'string') {

      switch (config.offset) {

        case 'left':
          config.offset = 0;
        break;

        case 'right':
          config.offset = tickerWidth;
        break;

        case 'center':
          config.offset = tickerWidth / 2;
        break;

        default:
          if (pctRegExp.test(config.offset)) {

            // Parse the percentage value from the string
            var pct = config.offset.match(pctRegExp)[1] / 100;

            // Trap the percentage between 0% and 100%
            pct = Math.max(Math.min(pct, 1), 0);

            config.offset = Math.round(pct * tickerWidth);
          }
        break;
      }
    }

    /**
     *  Handles the case of 'auto' by returning 0
     */
    var parseCSSPropertyValue = function(cssValue, radix) {
      return parseInt(cssValue, radix || 10) || 0;
    };

    /**
     *  Returns an elements actual width including left/right
     *  margins, padding, and borders
     */
    var computeActualWidth = function(item) {

      var w = item.width();

      $.each([
        'margin-left',
        'margin-right',
        'padding-left',
        'padding-right',
        'border-left-width',
        'border-right-width'
      ], function() {
        w += parseCSSPropertyValue(this);
      });

      return w;
    };

    var totalWidth = 0;
    var itemWidths = [];

    /**
     *  Initialize ticker items
     */
    items.each(function(i, item) {

      var $item = $(item);

      // Enforce required CSS for ticker container...
      // ...and position item in queue
      $item.css({
        position: 'absolute',
        whiteSpace: 'nowrap',
        left: totalWidth + config.offset
      });

      // Cache width to save us a call later on
      itemWidths[i] = computeActualWidth($item);

      // Increment the left offset of the next item.
      // Once finished, this value will contain the total
      // width of all elements.
      totalWidth += itemWidths[i];
    });

    // Pre-compute and cache the reset values for each item.
    // This isn't really a huge performance enhancement, but
    // it's good form to remove all unnecessary calculations
    // from inside loops.
    var itemResets = [];
    items.each(function(i, item) {
      itemResets[i] = totalWidth - itemWidths[i];
    });

    // Initial timer value
    var timer = null;

    /**
     *  Main ticker function
     */
    var animate = function() {

      items.each(function(i, item) {

        // NOTE: For better performance, we don't use jQuery inside the
        // tick method. The jQuery version skipped more frequently.
        // Original code included for reference.

        // NOTE: For better performance, I removed:
        // var $item = $(item);

        // For better performance, I replaced:
        // var left = parseCSSPropertyValue($item.css('left'));
        // with:
        var left = parseCSSPropertyValue(item.style.left);

        // If the element has moved completely out of
        // view, move it to the back of the queue.
        if (left + itemWidths[i] < 0) {
          left = itemResets[i];
        }

        // Move the element left by the configured distance
        left -= config.distance;

        // NOTE: For better performance, I replaced:
        // $item.css('left', left);
        // with:
        item.style.left = left + 'px';
      });

      // Set timer
      timer = window.setTimeout(animate, config.velocity);
    };

    /**
     *  Pause the ticker (for mouseovers)
     */
    var pause = function(e) {
      // Clear timer
      timer = window.clearTimeout(timer);
    };

    /**
     *  Assign event handlers to ticker.
     */
    ticker.hover(pause, animate);

    if (config.fade > 0) {
      items.fadeIn(config.fade);
    }

    animate();
  });
};



function getShoppingTicker(source, div, settings) {
    $.ajax({
        url: source,
        dataType: 'script',
        success: function() {
            handleJSON(shopstyle_trendsResult.trends, div, settings);
        }
    });
}

function handleJSON(trends, div, settings) {
    var e, l, p;
    for(var i=0; i<trends.length; i++) {
        p = trends[i];
        e = document.createElement('li');
        e.className = 'tickerItem';
        l = document.createElement('a');
        l.innerHTML = p.brand + " " + p.categoryName;
        l.href = p.product.seeMoreUrl;
        e.appendChild(l);
        e.innerHTML += '...';
        $(div).append(e);
    }
    $(div).tick(settings);
}
