(function() {
  var Countdown, bidding_history, change_auction, decrement_available_bids, new_bid, saving_perc, savings, start_counters, tag_price_value, trigger_hide_medium;
  Countdown = (function() {
    function Countdown(target_id, start_time) {
      this.target_id = target_id != null ? target_id : "#timer";
      this.start_time = start_time != null ? start_time : "600";
    }
    Countdown.baseline = undefined;
    Countdown.prototype.run = function() {
      var end, nextTick;
      if (this.baseline === undefined) {
        this.baseline = new Date().getTime();
      }
      this.tick();
      end = new Date().getTime();
      this.baseline += 1000;
      nextTick = 1000 - (end - this.baseline);
      if (nextTick < 0) {
        nextTick = 0;
      }
      return (function(i) {
        return i.timer = setTimeout(function() {
          return i.run(end);
        }, nextTick);
      })(this);
    };
    Countdown.prototype.stop = function() {
      return clearTimeout(this.timer);
    };
    Countdown.prototype.init = function() {
      this.finished = false;
      this.reset();
      this.timebase = void 0;
      return this.run();
    };
    Countdown.prototype.reset = function(val) {
      var minutes;
      if (val == null) {
        val = this.start_time;
      }
      this.seconds = val % 60;
      minutes = Math.floor((val - this.seconds) / 60);
      this.hours = Math.floor(minutes / 60);
      this.minutes = minutes % 60;
      return this.updateTarget();
    };
    Countdown.prototype.tick = function() {
      var hours, minutes, seconds, _ref;
      _ref = [this.seconds, this.minutes, this.hours], seconds = _ref[0], minutes = _ref[1], hours = _ref[2];
      if (hours > 0 || seconds > 0 || minutes > 0) {
        if (seconds === 0) {
          this.dec_minutes();
          this.seconds = 59;
        } else {
          this.seconds = seconds - 1;
        }
      }
      return this.updateTarget();
    };
    Countdown.prototype.dec_minutes = function() {
      var hours, minutes, seconds, _ref;
      _ref = [this.seconds, this.minutes, this.hours], seconds = _ref[0], minutes = _ref[1], hours = _ref[2];
      if (minutes > 0 || hours > 0) {
        if (minutes === 0) {
          this.hours = hours - 1;
          return this.minutes = 59;
        } else {
          return this.minutes = minutes - 1;
        }
      }
    };
    Countdown.prototype.to_string = function() {
      var hours, minutes, seconds, _ref;
      _ref = [this.seconds, this.minutes, this.hours], seconds = _ref[0], minutes = _ref[1], hours = _ref[2];
      if (seconds < 1 && minutes < 1 && hours < 1) {
        return "going..";
      } else {
        if (this.seconds < 10) {
          seconds = '0' + this.seconds;
        }
        if (this.minutes < 10) {
          minutes = '0' + this.minutes;
        }
        if (this.hours < 10) {
          hours = '0' + this.hours;
        }
        return "" + hours + ":" + minutes + ":" + seconds;
      }
    };
    Countdown.prototype.updateTarget = function() {
      if (this.hours === 0 && this.minutes === 0 && this.seconds < 10) {
        $(this.target_id).closest(".time").addClass("sub_ten_sec");
      }
      return $(this.target_id).html(this.to_string());
    };
    return Countdown;
  })();
  start_counters = function() {
    var client;
    client = new Faye.Client(host);
    return $('.auction[data-auction-state=active]').each(function(id, auction) {
      var auction_id, countdown, state, timer;
      state = $(auction).data('auction-state');
      auction_id = $(auction).data('auction-id');
      countdown = $("#auction_" + auction_id).data('countdown');
      timer = new Countdown("#auction_" + auction_id + " .countdown", countdown);
      timer.init();
      return client.subscribe('/' + auction_id, function(message) {
        if (message.cmd === 'new_bid') {
          return new_bid(auction_id, message, timer);
        } else if (message.cmd === 'state_change') {
          return change_auction(auction_id, message, timer);
        }
      });
    });
  };
  change_auction = function(auction_id, message, timer) {
    var container_class, show_auction_container;
    if (message.state === 'finished') {
      timer.stop();
      $("#notices").html("<div id='notice'> Auction " + auction_id + " Has Finished! <img class='flash_close' src='/images/close_button_black.png' /></div>");
      show_auction_container = $("#auction_" + auction_id + " .show_page_finished_state").parents('.auction');
      if ($(show_auction_container).length && ($(show_auction_container).hasClass('auction_full_view') || $(show_auction_container).hasClass('main_auction_detail_view'))) {
        container_class = $(show_auction_container).hasClass('auction_full_view') ? 'auction_full_view' : 'main_auction_detail_view';
        $("." + container_class + "#auction_" + auction_id).addClass("finished");
        $("." + container_class + "#auction_" + auction_id + " .show_page_finished_state").html("<div class='won_in_bid_count finished_auction'><span>Won in " + message.user_bid_amount + " bids by</span></div>");
        $("." + container_class + "#auction_" + auction_id + " .current_top_bidder img").attr('src', "" + message.user_avatar);
        $("." + container_class + "#auction_" + auction_id + " .current_top_bidder .name").html("" + message.username);
        $("." + container_class + "#auction_" + auction_id + " .lower_left_column .current_price, ." + container_class + "#auction_" + auction_id + " .auction_price .current_price").val("" + (tag_price_value(auction_id)));
        $("." + container_class + "#auction_" + auction_id + " .lower_left_column .savings").val("" + (savings(auction_id).toFixed(2)) + " (" + (saving_perc(auction_id)) + "%)");
      }
      if (!$("#auction_" + auction_id).hasClass('auction_full_view') || !$("#auction_" + auction_id).hasClass('main_auction_detail_view')) {
        $(".auction_container #auction_" + auction_id).addClass("finished");
        $(".auction_container #auction_" + auction_id + " .time").hide();
        $(".auction_container #auction_" + auction_id + " .auction_price").hide();
        $(".auction_container #auction_" + auction_id + " .current_top_bidder_auction").hide();
        $(".auction_container #auction_" + auction_id + " .hide_medium_type").hide();
        $(".auction_container #auction_" + auction_id + " .finished_state").html("<div class='current_price final_price finished_auction'>" + (tag_price_value(auction_id)) + "</div><div class='savings_finished_auction'><span>SAVED </span><span style='color:#6ab93d;'>" + (saving_perc(auction_id)) + "% OFF </span><span><span class='msrp'>MSRP</span></span></div><div class='won_in_bid_count finished_auction'><span>Won in " + message.user_bid_amount + " bids by</span><div class='name'><img src='" + message.user_avatar + "' /> " + message.username + "</div></div>");
      }
      if ($("#auction_quick_view_" + auction_id).is(':visible')) {
        $("#auction_quick_view_" + auction_id + " .time").show();
        $("#auction_quick_view_" + auction_id + " .show_page_finished_state").html("<div class='won_in_bid_count finished_auction'><span>Won in " + message.user_bid_amount + " bids by</span></div>");
        $("#auction_quick_view_" + auction_id + " .current_top_bidder img").attr('src', "" + message.user_avatar);
        $("#auction_quick_view_" + auction_id + " .current_top_bidder .name").html("" + message.username);
        $("#auction_quick_view_" + auction_id + " .right_column .current_price, #auction_quick_view_" + auction_id + " .auction_price .current_price").val("" + (tag_price_value(auction_id)));
        $("#auction_quick_view_" + auction_id + " .right_column .savings").val("" + (savings(auction_id).toFixed(2)) + " (" + (saving_perc(auction_id)) + "%)");
      }
      $("#auction_" + auction_id + " .current_price").formatCurrency({
        region: "" + user_locale
      });
      if (current_user_id.toString() === message.winner_id.toString()) {
        $("#auction_" + auction_id + " .main_button").removeClass("bid_here_button winning_auction green");
        $("#auction_" + auction_id + " .main_button").addClass("orange won_auction");
        $("#auction_" + auction_id + " .main_button").html("You Won!");
        return $("#auction_" + auction_id + " .countdown").html("--:--:--");
      } else {
        $("#auction_" + auction_id + " .main_button").removeClass("bid_here_button green");
        $("#auction_" + auction_id + " .main_button").addClass("grey sold");
        $("#auction_" + auction_id + " .main_button").html("SOLD");
        return $("#auction_" + auction_id + " .countdown").html("--:--:--");
      }
    } else if (message.state === 'halted') {
      timer.stop();
      $("#notices").html("<div id='notice'> Auction " + auction_id + " Has Been Halted! <img class='flash_close' src='/images/close_button_black.png' /></div>");
      $("#auction_" + auction_id + " .main_button").removeClass("bid_here_button green");
      $("#auction_" + auction_id + " .countdown").html("--:--:--");
      $("#auction_" + auction_id + " .main_button").addClass("grey sold");
      return $("#auction_" + auction_id + " .main_button").html("HALTED");
    }
  };
  tag_price_value = function(auction_id) {
    var auction, bid_increment, ceiling, floor, tag_price, total_bids;
    auction = $("#auction_" + auction_id);
    total_bids = parseInt(auction.data('total_bids'));
    bid_increment = parseFloat(auction.data('bid_increment'));
    floor = parseFloat(auction.data('floor'));
    ceiling = parseFloat(auction.data('ceiling'));
    tag_price = total_bids * bid_increment;
    if (tag_price < floor) {
      tag_price = floor;
    }
    if (tag_price > ceiling) {
      tag_price = ceiling;
    }
    if (auction.data('zero')) {
      tag_price = 0.0;
    }
    if (auction.data('fixed_price')) {
      tag_price = auction.data('fixed_price_value');
    }
    return tag_price;
  };
  savings = function(auction_id) {
    var auction, price, saving;
    auction = $("#auction_" + auction_id);
    price = tag_price_value(auction_id);
    saving = parseFloat(auction.data("msrp")) - parseFloat(price);
    return saving;
  };
  saving_perc = function(auction_id) {
    var auction, msrp, perc, price_for_perc;
    auction = $("#auction_" + auction_id);
    price_for_perc = tag_price_value(auction_id);
    msrp = parseFloat(auction.data("msrp"));
    return perc = Math.round((1.0 - price_for_perc / msrp) * 100);
  };
  new_bid = function(auction_id, message, timer) {
    var count_history, datetime;
    datetime = new Date();
    $("#auction_" + auction_id).data('total_bids', message.total_bids);
    $("#auction_" + auction_id + " .savings").html("" + currency_symbol + (savings(auction_id).toFixed(2)) + " (" + (saving_perc(auction_id)) + "%)");
    $("#auction_" + auction_id + " .bids").html("Total bids: " + message.total_bids);
    $("#auction_" + auction_id + " .time").removeClass("sub_ten_sec");
    $("#auction_" + auction_id + " .time").effect("highlight", {}, 1000);
    $("#auction_" + auction_id + " .bid_history_list tbody").prepend(bidding_history(message, datetime));
    count_history = $("#auction_" + auction_id + " .bid_history_list tbody tr").length;
    if (count_history > 10) {
      $("#auction_" + auction_id + " .bid_history_list tbody tr").slice(-(count_history - 10)).remove();
    }
    $("#auction_" + auction_id + " .current_price").html("" + currency_symbol + " " + (tag_price_value(auction_id).toFixed(2)));
    $("#auction_" + auction_id + " .current_price").formatCurrency({
      region: "" + user_locale
    });
    $("#auction_" + auction_id + " .auction_price").textfill();
    $("#auction_" + auction_id + " .current_top_bidder").html("<img src='" + message.user_avatar + "' /><div class='name'>" + message.username + "</div>");
    $("#auction_" + auction_id + " .current_top_bidder_auction").html("<img src='" + message.user_avatar + "' /><div class='name'>" + message.username + "</div>");
    $("#auction_" + auction_id + " .won_in_bid_count span").html("<img src='" + message.user_avatar + "' /><div class='name'>" + message.username + "</div>");
    if (current_user_id.toString() === message.bid_user_id.toString()) {
      $("#auction_" + auction_id + " #form_auction_" + auction_id).addClass("winning_auction orange");
      $("#auction_" + auction_id + " #form_auction_" + auction_id).removeClass("bid_here_button green");
      $("#auction_" + auction_id + " #form_auction_" + auction_id).html("You're Leading");
      if (message.buy_now_price < 0) {
        $("#auction_" + auction_id + " .buy_now_price").html("" + currency_symbol + "0.00");
        $("#auction_" + auction_id + " .buy_now_savings").html("" + currency_symbol + (message.shipping_costs.toFixed(2)));
      } else {
        $("#auction_" + auction_id + " .buy_now_price").html("" + currency_symbol + (message.buy_now_price.toFixed(2)));
        $("#auction_" + auction_id + " .buy_now_savings").html("" + currency_symbol + (message.total_costs.toFixed(2)));
      }
    } else {
      $("#auction_" + auction_id + " #form_auction_" + auction_id).html("bid");
      $("#auction_" + auction_id + " #form_auction_" + auction_id).removeClass("winning_auction orange");
      $("#auction_" + auction_id + " #form_auction_" + auction_id).addClass("bid_here_button green");
    }
    return timer.reset(message.countdown);
  };
  bidding_history = function(message, datetime) {
    var elem;
    elem = "<tr>     <td class='avatar'><img src='" + message.user_avatar + "' width='50' height='50'/></td>     <td class='username'>" + message.username + "</td>     <td class='bid_time'>" + message.bid_time + "</td>     <td class='medium'>" + message.type + "</td>     </tr>";
    return elem;
  };
  trigger_hide_medium = function(checkbox, auction_id) {
    return $.ajax({
      type: 'POST',
      url: "/auctions/" + auction_id + "/hide_unhide_medium.json",
      dataType: 'json',
      success: function(data) {
        console.log("checkbox", checkbox);
        return $(checkbox).attr('checked', data != null ? data : {
          'checked': ''
        });
      },
      error: function(data) {
        return alert("Error: " + data);
      }
    });
  };
  decrement_available_bids = function() {
    var bids, el;
    el = $('#bid_count');
    bids = parseInt(el.html());
    el.html(--bids);
    return $('.bidcount').html(bids);
  };
  $(document).ready(function() {
    var monkey_submit;
    $.ajax({
      type: 'GET',
      url: '/auctions/get_timers.json',
      dataType: 'json',
      success: function(data) {
        var a, _i, _len;
        for (_i = 0, _len = data.length; _i < _len; _i++) {
          a = data[_i];
          $("#auction_" + a.id).data('countdown', a.countdown);
        }
        return start_counters();
      }
    });
    window.upd_bids = function() {
      return $.ajax({
        type: 'get',
        url: '/bids_left.json',
        dataType: 'json',
        success: function(data) {
          var bm, _i, _len, _ref, _results;
          $('#bid_count').html(data.bids);
          $('.bidcount').html(data.bids);
          _ref = data.bidmonkeys;
          _results = [];
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            bm = _ref[_i];
            $(".bids_spent[data-bidmonkey-id='" + bm.id + "']").html(bm.spent_bids);
            _results.push($(".total_spent[data-bidmonkey-id='" + bm.id + "']").html(bm.total_spent));
          }
          return _results;
        }
      });
    };
    setInterval(window.upd_bids, 30000);
    $('.corner_mag_button').click(function() {
      var auction_id;
      auction_id = $(this).parents().data('auction-id');
      return $.ajax({
        type: 'GET',
        url: '/auctions/' + auction_id + '/quick_view',
        dataType: 'script',
        success: function(data) {
          return $("#auction_quick_view_" + auction_id).html("" + data);
        },
        error: function() {
          return $("#auction_quick_view_" + auction_id).html("<div id='alert'>Quick View Failed, try again.</div>");
        }
      });
    });
    $('.show_bids_history').click(function() {
      var auction_id, user_id, with_protectors;
      auction_id = $(this).data('auction-id');
      user_id = $(this).data('user-id');
      with_protectors = '';
      if ($("#with_protectors").length > 0 && $("#with_protectors").is(":checked")) {
        with_protectors = '&with_protectors=1';
      }
      return $.ajax({
        type: 'GET',
        url: '/admin/auctions/' + auction_id + '/show_bids',
        data: ("user_id=" + user_id) + with_protectors,
        dataType: 'script',
        error: function() {
          return $("#auction_bids_list_" + user_id).html("<div id='alert'>Bids History Failed, try again.</div>");
        }
      });
    });
    $('#bid_monkey_show_confirm').live('click', function(e) {
      $('#bid_monkey_show_confirm').hide();
      return $('#bid_monkey_stop_button').show();
    });
    $('.reverse_auction_overlay').click(function() {
      var auction_id;
      auction_id = $(this).data('auction-id');
      return $.ajax({
        type: 'GET',
        url: '/admin/auctions/' + auction_id + '/reverse_bids_users',
        dataType: 'script',
        error: function() {
          return $("#reverse_bids_" + auction_id).html("<div id='alert'>Quick View Failed, try again.</div>");
        }
      });
    });
    monkey_submit = function(e) {
      var auction_id, element, form, monkey_attributes;
      form = $(this).parents('form');
      monkey_attributes = $(this).parents('form').serialize();
      auction_id = $(this).parents('.monkey_form').data('auction-id');
      element = $(e.target);
      return $.ajax({
        type: 'POST',
        url: form.attr('action'),
        dataType: 'json',
        data: monkey_attributes,
        success: function(data) {
          var container, form_container;
          if (data.status === 'address_error' || data.status === 'premium_error') {
            $.alerts.dialogClass = 'no-address-popup';
            $.alerts.overlayOpacity = '0.8';
            $.alerts.overlayColor = 'black';
            return jAlert('<div id="shipping_alert">' + data.message + '</div>', data.title);
          } else if (data.bid_monkey === void 0 && data.status !== void 0 && data.status === 'bidder_is_bought_error') {
            return $(".monkey_form").prepend("<div id='alert'>" + data.message + "</div>");
          } else {
            form_container = element.parents('.monkey_form');
            form_container.find('.sidebar_new_form_container').hide();
            if (form_container.find('.add_bids input[name="_method"]')) {
              form_container.find('.add_bids input[name="authenticity_token"]').append('<input type="hidden" name="_method" value="put" />');
            }
            if (form_container.find('.sidebar_new_form_container input[name="_method"]')) {
              form_container.find('.sidebar_new_form_container input[name="authenticity_token"]').append('<input type="hidden" name="_method" value="put" />');
            }
            container = form_container.find('.sidebar_monkey_container').show();
            container.find('.bid_start').text(data.bid_monkey.bid_start);
            container.find('.bid_end').text(data.bid_monkey.bid_end);
            container.find('.bids_allocated').text(data.bid_monkey.bids_allocated);
            container.find('.add_bids form');
            form_container.find('form').attr('action', '/bid_monkeys/' + data.bid_monkey.id);
            $('#bid_monkey_show_confirm').show();
            return $('#bid_monkey_stop_button').hide();
          }
        },
        error: function(data, r) {
          return $(".monkey_form").prepend("<div id='alert'>Setting your monkey failed, do you have enough bids?</div>");
        }
      });
    };
    $('#bid_monkey_submit').live('click', monkey_submit);
    $('.monkey_quick_submit').live('click', monkey_submit);
    $('.bid_here_button').live('click', function(el) {
      var auction_id;
      auction_id = $(this).data('auction-id');
      el.preventDefault();
      return $.ajax({
        type: 'POST',
        url: '/bids',
        dataType: 'json',
        data: 'bid[auction_id]=' + auction_id,
        success: function(data) {
          if (data.status === 'address_error' || data.status === 'bidder_is_bought_error' || data.status === 'premium_error') {
            $.alerts.dialogClass = 'no-address-popup';
            $.alerts.overlayOpacity = '0.8';
            $.alerts.overlayColor = 'black';
            return jAlert('<div id="shipping_alert">' + data.message + '</div>', data.title);
          } else {
            return decrement_available_bids();
          }
        },
        error: function() {
          return jAlert('Looks like you do not have enough bids.<a href = "/bidpacks" class="main_button orange" id="pop_up_bid_button">Buy Bids Now!</a>', 'Out of Bids?');
        }
      });
    });
    $('.bid_here_button_quick').live('click', function(el) {
      var auction_id;
      auction_id = $(this).data('auction-id');
      el.preventDefault();
      return $.ajax({
        type: 'POST',
        url: '/bids',
        dataType: 'script',
        data: 'bid[auction_id]=' + auction_id,
        success: function() {
          if (data.status === 'address_error') {
            $.alerts.dialogClass = 'no-address-popup';
            return jAlert('<div id="shipping_alert">' + data.message + '</div>', data.title);
          } else {
            $("#auction_" + auction_id + " #form_auction_" + auction_id).addClass("winning_auction orange");
            $("#auction_" + auction_id + " #form_auction_" + auction_id).removeClass("bid_here_button_quick green");
            $("#auction_" + auction_id + " #form_auction_" + auction_id).html("You're Leading");
            $("#auction_" + auction_id + " .sms_button").hide();
            return decrement_available_bids();
          }
        },
        error: function() {
          return jAlert('Looks like you do not have enough bids.<a href = "/bidpacks" class="main_button orange" id="pop_up_bid_button">Buy Bids Now!</a>', 'Out of Bids?');
        }
      });
    });
    return $('.hide_medium').live('click', function() {
      var el;
      console.log("Iam", this);
      el = $(this);
      if (!el.data('allowed_to_hide')) {
        return jConfirm("Are you sure you want to spend " + ($(this).data('hide_medium_cost')) + " bids to enable this feature?", "Are you Sure", function(ans) {
          if (ans) {
            el.data('allowed_to_hide', true);
            return trigger_hide_medium(el, el.data('auction_id'));
          }
        });
      } else {
        return trigger_hide_medium(el, el.data('auction_id'));
      }
    });
  });
}).call(this);

