var has_filtered = false;

rotate_coupon = function(){
  if ((next = $('#featured_coupons li.active').next()).get(0) == null) {
    next = $('#featured_coupons li:first');
  }
  $('#coupon_chooser_' + $(next.attr('id').split('_')).last().get(0)).trigger('click');
}

stop_coupon_rotation = function() {
  $(document).stopTime("featured_coupons_rotator");
  $('#coupon_choosers #play').removeClass('enabled');
  $('#coupon_choosers #pause').addClass('enabled');
}
start_coupon_rotation = function() {
  /* if the customer has manually paused the rotation, don't restart */
  if($('#coupon_choosers #pause').hasClass('manual')) { return; }

  $(document).everyTime('5s', "featured_coupons_rotator", rotate_coupon);
  $('#coupon_choosers #pause').removeClass('enabled');
  $('#coupon_choosers #play').addClass('enabled');
}

get_arguments = function() {
  var matches,url,path,domain;
  url=document.location.toString();
  try {
    domain=url.match(/https?:\/\/[^\/]+/);
    if (matches=url.match(/(.+?)#(.+)/)) {
      var filter, order, area;
      $.each($(matches).last().get(0).split('&'), function(index, match) {
        if ((result=$(match.split(/filter\?/))).length > 1) {
          filter = result.last().get(0);
        } else if ((result=$(match.split(/order\?/))).length > 1) {
          order = result.last().get(0);
        } else if ((result=$(match.split(/area\?/))).length > 1) {
          area = result.last().get(0);
        }
      });
    }
    return {'filter': filter || null, 'order': order || null, 'area': area || null};
  }
  catch(err){};
}

var last_coupon_id_previously = null;
var last_coupon_id = -1;
get_todays_coupons = function(regardless, limit, override_rather_than_append, scroll_when_finished){
  item_height = 103; item_spacing = 27;
  coupons_list = $('#todays_coupons');
  var scrollTop = ($(document).scrollTop() || $(coupons_list.get(0).ownerDocument.body).scrollTop());

  if (regardless == true || ($(document).height() - scrollTop - $(window).height()) < 150) {
    required_items = limit || (Math.ceil(
      ($(document).height() - (
        coupons_list.offset().top + coupons_list.height()
      )) / (item_height + item_spacing)
    ) * 2) + 4;

    if (required_items > 0) {
      items = $('#todays_coupons li');
      $(document).unbind('scroll', get_todays_coupons);
      args = {limit: required_items, count: items.length};
      other_args = get_arguments();
      if ((filter=other_args.filter) != null && filter.length > 0) {
        args = $.extend(args, {'filter': filter});
      }
      if ((order=other_args.order) != null && order.length > 0) {
        args = $.extend(args, {'order': order});
      }
      if ((area=other_args.area) != null && area.length > 0) {
        args = $.extend(args, {'area': area});
      }
      if (items.length > 0) {
        last_coupon_id = $(items.last().attr('id').split('_')).last().get(0);
        $.extend(args, {last: last_coupon_id});
      }
      if (last_coupon_id_previously != last_coupon_id) {
        $.get(todays_coupons_url, args, function(data) {
          // strip out blank text nodes.
          data = $(data).filter(function(){return this.nodeType != 3;});
          existing_coupon_count = coupons_list.find('li').length;
          if ((last_coupon = coupons_list.find('li').last()).length == 1) {
            last_coupon_id_previously = $(last_coupon.attr('id').split('_')).last().get(0);
          }

          // only keep going if we receive as many items as we ask for because there may be more.
          if ((new_items = $(data)).length == required_items) {
            $(document).scroll(get_todays_coupons);
          }

          coupons_list.css({height: 'auto'}).css({'max-height': coupons_list.height(), overflow:'hidden'});
          if (override_rather_than_append) {
            coupons_list.parent().find('h3, #clear_filters').remove();
            coupons_list.find('li').remove();
          }
          new_items.appendTo(coupons_list);
          animate_to_max_height = Math.ceil((existing_coupon_count + required_items) / 2) * ( item_height + item_spacing );
          timeout = (regardless ? 0 : 500);
          coupons_list.animate({'max-height': animate_to_max_height}, timeout, function() {
            if (scroll_when_finished){
              scroll_to_todays_coupons();
            }
          });

          add_title_for_coupons();
        });

        add_title_for_coupons();
      }
    } else {
      $(document).scroll(get_todays_coupons);
    }
  }
}

scroll_to_todays_coupons = function() {
  var targetOffset = $('#todays_coupons_filter_top').offset().top;
  if (targetOffset > $(document).scrollTop() || $($('#todays_coupons').get(0).ownerDocument.body).scrollTop()) {
    $('html,body').animate({scrollTop: targetOffset}, 250);
  }
}

apply_new_argument = function(argument, href, trigger_ajax, current_arguments) {
  has_filtered = true;

  if (current_arguments == null) {
    current_arguments = get_arguments();
  }
  if (argument != "order") {
    apply_default_order(current_arguments);
  }

  item_height = 103; item_spacing = 27;
  if (argument != null && argument.length > 0) {
    if ((current_location = document.location.toString()).indexOf("#") > -1) {
      // delete the current setting.
      if (current_location.indexOf(argument + "?") > -1) {
        if (href != null && href.length > 0) {
          last_part = $(href.split('/')).last().get(0).replace('#', '');
          if ((split_by_category=$(href.split('/categories/'))).length > 1) {
            href = current_location.replace(new RegExp('(filter\\?[^&]+)'), ("filter?" + last_part));
            if (href.indexOf("filter?") < 0) {
              href = current_location + "&filter?" + last_part;
            }
          } else {
            href = current_location.replace(new RegExp('(' + argument + '\?)([^&]+)'), "$1?" + $(href.split('?')).last().get(0));
          }
        } else {
          href = current_location.replace(new RegExp('(&?' + argument + '\?)([^&]+)'), '');
        }
      } else {
        if (href != null && href.length > 0) {
          last_part = $(href.split('/')).last().get(0).replace('#', '');
          if ((split_by_category=$(href.split('/categories/'))).length > 1) {
            href = current_location.replace(new RegExp('(filter\\?[^&]+)'), ("filter?" + last_part));
            if (href.indexOf("filter?") < 0) {
              href = current_location + "&filter?" + last_part;
            }
          } else {
            href = current_location + "&" + last_part;
          }
        } else {
          href = current_location;
        }
      }
    }
    window.location = href;
  }
  if (trigger_ajax) {
    coupons_list = $('#todays_coupons');
    previous_coupon_count = coupons_list.find('li').length;
    coupons_list.animate({'max-height': '0px', overflow: 'hidden'}, 0, function() {
      last_coupon_id_previously = null;
      coupons_list.parent().find('h3, #clear_filters').remove();
      coupons_list.find('li').remove();
      get_todays_coupons(true, ((previous_coupon_count <= 4) ? 4 : (previous_coupon_count % 2 == 1 ? previous_coupon_count+1 : previous_coupon_count)), true, true);
      add_title_for_coupons();
    });
  }
}

add_title_for_coupons = function(existing_coupon_count) {
  if (has_filtered) {
    title = "<h3>{start_order}{filter}Coupons{area}{end_order}</h3>";
    existing_coupon_count = (typeof(existing_coupon_count) == "undefined" ? 0 : existing_coupon_count);
    if (filter != null && filter.length > 0 && existing_coupon_count == 0) {
      title = title.replace("{filter}", ($('#todays_coupons_filter li.selected > a').html() || "").replace(/<\/?.+?>/, '').replace(/<\/?.+?>/, '') + " ");
    }
    if (order !=null && order.length > 0 && existing_coupon_count == 0) {
      if (order == "popular") {
        title = title.replace("{start_order}", "Most Popular ");
      }
      if (order == "newest") {
        title = title.replace("{start_order}", "Newest ");
      }
      if (order == "savings") {
        title = title.replace("{end_order}", " with the Biggest Savings");
      }
    }
    if (area != null && area.length > 0 && existing_coupon_count == 0) {
      title = title.replace("{area}", " in " + $('#todays_coupons_area_filter li.selected > a').html());
    }

    title = title.replace('{filter}', '').replace('{area}', '').replace('{start_order}', '')
                 .replace('{end_order}', '');

    if ((h3 = $('#todays_coupons').parent().find('h3').not('.coupon h3')).length == 0) {
      $(title).prependTo($('#todays_coupons').parent()).after($("<a href='/' id='clear_filters'>(clear)</a>"));
    } else {
      // title already exists, replace it.
      h3.html(title.replace(/<\/?h3>/, '').replace(/<\/?h3>/, ''));
      if ($('#clear_filters').length == 0) {
        h3.after($("<a href='/' id='clear_filters'>(clear)</a>"))
      }
    }
  }
}

apply_default_order = function(trigger_order, current_arguments){
  need_to_get_coupons = true;
  if (current_arguments == null) {
    current_arguments = get_arguments();
  }
  current_order = $('#todays_coupons_subfilter').find('a[href$=order?' + current_arguments.order + ']');
  if (current_order.length == 0) {
    current_order = $('#todays_coupons_subfilter li a:first');
    if (trigger_order) {
      apply_new_argument("order", current_order.attr('href'), false, current_arguments);
    }
    need_to_get_coupons = false;
  }
  current_order.parent().addClass('selected');

  return need_to_get_coupons;
}

$(document).ready(function(e) {
  start_coupon_rotation();
  current_arguments = get_arguments();

  $('span.coupon_chooser').click(function(e) {
    $('#featured_coupons > li.active').removeClass('active').hide();
    $("#" + $(this).attr('id').replace('coupon_chooser', 'featured_coupon')).addClass('active').show();
    $('span.coupon_chooser').each(function(index, span) {
      $(this).removeClass('enabled');
    });
    $(this).addClass('enabled');
    stop_coupon_rotation();
    start_coupon_rotation();
  });

  $('#featured_coupons').hover(
    stop_coupon_rotation, start_coupon_rotation
  );
  $('#coupon_choosers #pause').click(function(e) {
    $('#coupon_choosers #pause').addClass('manual');
    stop_coupon_rotation();
  });
  $('#coupon_choosers #play').click(function(e) {
    $('#coupon_choosers #pause').removeClass('manual');
    start_coupon_rotation();
  });

/*  $('#todays_coupons_subfilter a').click(function(e) {
    $('#todays_coupons_subfilter li.selected').removeClass('selected');
    $(this).parent().addClass('selected');

    apply_new_argument("order", $(this).attr('href'), true);

    current_arguments = get_arguments();
    possible_analytics_event(analytics_enabled, analytics_code, 'Home Page', 'Order', current_arguments.order);
    e.preventDefault();
  });*/

/*  $('#todays_coupons_area_filter a').click(function(e) {
    $('#todays_coupons_area_filter li.selected').removeClass('selected');
    $(this).parent().addClass('selected');
    (span = $('#todays_coupons_area_filter span:first span')).css('width', span.width()).html($(this).html());

    apply_new_argument("area", $(this).attr('href'), true);

    if ($(this).html() == "View all neighborhoods") {
      $('#todays_coupons_area_filter span span').html("See coupons from your neighborhood");
    }

    current_arguments = get_arguments();
    possible_analytics_event(analytics_enabled, analytics_code, 'Home Page', 'Neighborhood', current_arguments.area);

    e.preventDefault();
  });*/

  $('#todays_coupons_area_filter').hover(function(e) {
    $(this).addClass('hovering');
    (img = $(this).find('span img')).attr('src', img.attr('src').replace('.png', '_hovering.png'));
    $(this).corner("top");
  }, function(e) {
    $(this).removeClass('hovering');
    (img = $(this).find('span img')).attr('src', img.attr('src').replace('_hovering.png', '.png'));
    $(this).corner("top");
  });

  $('#todays_coupons_filter > ul').hover(function(e) {
    possible_analytics_event(analytics_enabled, analytics_code, 'Home Page', 'Todays Coupons', 'Hover');
  }, function(e) {});

  $('#todays_coupons_area_filter').find('a[href$=area?' + current_arguments.area + ']').parent().addClass('selected');

  need_to_get_coupons = apply_default_order(false, current_arguments);
  if (current_arguments.filter != null || current_arguments.area != null) {
    need_to_get_coupons = true;
  }

  if (need_to_get_coupons) {
    get_todays_coupons(true, 8, true);
  }
});
