// Copyright (c) 2009-2010 A Main Hobbies

var new_campaign = new Object();
new_campaign.sizes = new Array();
new_campaign.dims = new Array();
new_campaign.dims[0] = [550, 350];
new_campaign.sizes[0] = "width='550' height='350'";
new_campaign.cycle = new Array();
new_campaign.slots = new Array();
new_campaign.loaded = 0;
new_campaign.current_slide = 0;
new_campaign.master_slot = 0;
new_campaign.timeout = 4000;

new_campaign.onBeforeCycle = function(currSlideElement, nextSlideElement, opts, forwardFlag)
{
  var slot = ($(this).attr('slot') | 0);

  // set the URL for the link container
  $(nextSlideElement).closest('a.slideshow').attr('href', $(nextSlideElement).attr('target_url'));

  if (slot != this.master_slot)
    return;

  if (opts.multiFx)
  {
    switch (opts.currFx)
    {
      case 'scrollDown':
           opts.easeIn = opts.easeOut = 'bounceout';
           break;

      case 'shuffle':
           opts.easeIn = opts.easeOut = 'easeout';
           break;

      default:
          opts.easeIn = opts.easeOut = 'linear';
          if (opts.currFx != 'shuffle' && opts.currFx != 'fade')
          {
            switch (opts.lastFx % 3)
            {
              case 0: opts.easeIn = opts.easeOut = 'bounceout'; break;
              case 1: opts.easeIn = opts.easeOut = 'backout'; break;
              case 2: opts.easeIn = opts.easeOut = 'easeout'; break;
            }
          }
          break;
    }
  }
}

new_campaign.onAfterCycle = function(currSlideElement, nextSlideElement, opts, forwardFlag)
{
}

new_campaign.ShowSlide = function(index)
{
  clearTimeout(this.timer_id);
  if (this.pager != null)
  {
    $(this.pager).find('a').removeClass('activeSlide');
    $(this.pager).find('a[index="' + index + '"]').addClass('activeSlide');
  }
  $(this.inner_container).children("a.slideshow").cycle(index);
  this.timer_id = window.setTimeout(this.SlideTimer, this.timeout);
};

new_campaign.PagerClick = function(obj)
{
  var action = $(obj).attr('action');
  var num_slides = $(this.slots[this.master_slot]).find('img[is_loaded=1]').length;

  if ($(obj).hasClass('unloadedSlide'))
    return false;

  if (action == 'nav_prev')
  {
    if (--this.current_slide < 0)
      this.current_slide = num_slides - 1;
  }
  else if (action == 'nav_next')
  {
    if (++this.current_slide >= num_slides)
      this.current_slide = 0;
  }
  else if (action == 'nav_select')
  {
    var position = $(obj).attr('index') | 0;
    if (position < num_slides)
      this.current_slide = position;
  }

  this.ShowSlide(this.current_slide);

  return false;
};

new_campaign.SlideTimer = function()
{
  var campaign = new_campaign;
  var num_slides = $(campaign.slots[campaign.master_slot]).find('img[is_loaded=1]').length;

  if (++campaign.current_slide >= num_slides)
    campaign.current_slide = 0;
  campaign.ShowSlide(campaign.current_slide);
}

new_campaign.LoadQTimer = function()
{
  var campaign = new_campaign;
  var num_slots = campaign.slots.length;
  var count = $(campaign).queue('loadQ').length;

  // dequeue at most one event per slot per call
  if (count > num_slots)
    count = num_slots;
  while (count--)
    $(campaign).dequeue('loadQ');

  var complete = $(campaign).queue('loadQ').length == 0;
  for (var i = 0; i < num_slots && complete == true; i++)
    if ($(campaign.slots[i]).children('img[is_loaded=0]:not(.image_preload)').length > 0)
      complete = false;
  if (!complete)
    setTimeout(campaign.LoadQTimer, 100);
}

new_campaign.ImageLoaded = function(obj, slot_id, status)
{
  var num_slots = this.slots.length;
  var this_campaign = this;

  // if (status == false)
    // console.debug("Load failed for " + $(obj).attr('src'));

  // mark as loaded ('complete' isn't findable as an attribute)
  // we do this even if the load failed, as there's not much we can do about it
  $(obj).attr('is_loaded', 1);

  // if loaded is 0 then we need to remove the loading image and show the image just loaded
  if (this.loaded == 0)
  {
    $(this.slots[slot_id]).children('img.image_preload.image_preload_static').remove();
    $(obj).show();
  }

  // we don't do anything else unless all pending images for this campaign have been loaded
  var complete = true;
  for (var i = 0; i < num_slots && complete; i++)
    if ($(this.slots[i]).children('img[is_loaded=0]:not(.image_preload)').length > 0)
      complete = false;

  if (!complete)
    return;

  // queue the next batch of images tagged with the 'image_preload' class
  for (var i = 0; i < num_slots; i++)
  {
    var img = $(this.slots[i]).children('img.image_preload:first');
    $(img).removeClass('image_preload');
    $(img).error(function(){var t = this; $(this_campaign).queue('loadQ', function(){this_campaign.ImageLoaded(t, i, false)})});
    $(img).load(function(){var t = this; $(this_campaign).queue('loadQ', function(){this_campaign.ImageLoaded(t, i, true)})});
    $(img).attr('src', $(img).attr('imgsrc'));
  }

  // adjust the pager enable state
  if (this.pager != null)
    $(this.pager).children('a.unloadedSlide:first').removeClass('unloadedSlide');

  // increment the load counter
  this.loaded++;

  // if we have exactly two loaded, enable the pager, start the timer, and kick off the slideshow
  if (this.loaded == 2)
  {
    // enable the pager, if present
    if (this.pager != null)
      $(this.pager).children('a').unbind('click').click(function() { this_campaign.PagerClick(this); });

    // set up the slideshow
    for (var i = num_slots - 1; i >= 0; i--)
      if (i != this.master_slot)
        $('.new_campaign_slideshow' + i).cycle(this.cycle[i]);
    $('.new_campaign_slideshow' + this.master_slot).cycle(this.cycle[this.master_slot]);

    // start the timer
    this.timer_id = window.setTimeout(this.SlideTimer, this.timeout);
  }
}

new_campaign.CycleSetup = function()
{
  var container = $('.new_campaign_inner_container');
  var slots = $(container).children('.slideshow').get();
  var num_slots = slots.length;

  // keep a copy of the slots in the object instance
  this.slots = slots;

  // store the containers, too
  this.outer_container = $('.new_campaign_outer_container');
  this.inner_container = container;

  var image_data = new Array();
  for (var i = 0; i < num_slots; i++)
  {
    image_data[i] = new Array();

    var image_list = $(slots[i]).children('input.image_prototype').get();
    var image_count = image_list.length;

    $(slots[i]).children('input.image_prototype').each(function()
    {
      // build the list of images from the data embedded in the DOM
      image_data[i].push({
          src: $(this).attr('img_src'),
          title: $(this).attr('title'),
          target: $(this).attr('target_url'),
          subindex: $(this).attr('subindex'),
          width: $(this).attr('w'),
          height: $(this).attr('h'),
          container: $(this).attr('container'),
          slot: $(this).attr('slot'),
          important: $(this).attr('important') != 0
        });
    });
  }

  // cull the list of images until it's no longer than max_slides entries (or we run out of attempts).
  // we keep images marked as 'important', so they are always in the rotation.
  for (var i = 0; i < num_slots; i++)
  {
    for (var attempts = 0; attempts < 50 && image_data[i].length > 20; attempts++)
    {
      var local_index = Math.floor(Math.random() * image_data[i].length);
      if (!image_data[i][local_index].important)
        image_data[i].splice(local_index, 1);
    }
  }

  // choose random starting slide number
  var starting_slide = new Array();
  for (var i = 0; i < num_slots; i++)
    starting_slide[i] = Math.floor(Math.random() * Math.min(image_data[i].length, 20));

  for (var i = 0; i < num_slots; i++)
  {
    var loading_img = $(this.slots[i]).children('img.image_preload_static:first').attr('src');
    var image_server = '';
    var pattern = new RegExp("^https?://.*[^/]$");

    if (typeof(window['campaign_image_server']) == 'string')
      if (window['campaign_image_server'].search(pattern) != -1)
        image_server = window['campaign_image_server'];

    // remove the place-holder input fields
    $(slots[i]).children('input.image_prototype').remove();

    // set up the images
    var html = '';
    for (var j = 0; j < image_data[i].length; j++)
    {
      var data = image_data[i][(j + starting_slide[i]) % image_data[i].length];
      var src = data.src;

      if (src.indexOf('://') == -1)
        src = image_server + src;

      html += '<img alt="' + data.title + '" title="' + data.title + '" target_url="' + data.target + '"' +
                 ' width="' + data.width + '" height="' + data.height + '"' +
                 ' style="display: none;" is_loaded="0" index="' + j + '"';
      if (j == 0)
        html += ' onload="new_campaign.ImageLoaded(this, ' + i + ', true)" src="' + src + '" class="slideshow_image">';
      else
        html += ' imgsrc="' + src + '" src="' + loading_img + '" class="slideshow_image image_preload">';
    }
    $(slots[i]).append(html);
  }

  // store the pager, if it exists
  this.pager = null;
  var pager = $(this.outer_container).children('div.slideshow_nav').get();
  if (pager.length > 0)
    this.pager = pager[0];

  // set the active slide highlight in the pager
  if (this.pager != null)
    $(this.pager).find('a[index=0]').addClass('activeSlide');

  window.setTimeout(this.LoadQTimer, 100);
}

new_campaign.cycle[0] = {fx: 'scrollDown,fade,fadeZoom,scrollLeft,growX', before: new_campaign.onBeforeCycle, after: new_campaign.onAfterCycle, timeout: 0, easing: 'backout', fastOnEvent: 0, containerResize: 0};
$(document).ready(function() { new_campaign.CycleSetup(); });
