$.fn.sort = function() {
  return this.pushStack($.makeArray([].sort.apply(this, arguments)));
};

$.fn.reverse = Array.reverse;

Array.max = function( array ){
  return Math.max.apply( Math, jQuery.makeArray(array) );
};

Array.min = function( array ){
  return Math.min.apply( Math, array );
};

var ViewPort = {
  center: function(targetWidth, targetHeight) {
    var win = $(window);
    var target = {
      top: Math.round((win.height()-targetHeight)/2)+win.scrollTop(),
      left: Math.round((win.width()-targetWidth)/2)+win.scrollLeft()
    };
    if (target.top < 0)  { target.top = 0;  }
    if (target.left < 0) { target.left = 0; }
    return target;
  }
};

$(function() {

  $.ajaxSetup({
    data: { authenticity_token : AUTH_TOKEN },
    type: 'POST',
    dataType: "json",
    beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }
  });

  $(document).bind("cart::updated", function(evt, response) {
    if (response !== null && response.cart_item_count >= 0) {
      $('.cart_count').html("(" + response.cart_item_count + ")");
    }
  });

/* Drop Downs
----------------------------------------- */

  $("#header_review_rank #review_badge").hover(function(){
    $("#header_review_rank #review_rank_popup").fadeIn('fast');
  }, function(){
    $("#header_review_rank #review_rank_popup").hide();
  });

    var populate_nav_popup = function(popup, self){
      if(self.is(".other_ways_wrapper")){
        popup.find(".content").append($(".other_ways_content").show()).addClass("ow");
      } else {
        popup.find(".content a").remove();
        popup.find(".content").append("<a href='"+ self.find("a").attr("href") +"'>"+ self.attr('alt') +"</a>");
        if (self.attr('alt').split(" ").length == 1){
          popup.find('a').css("height", "22px");
        }
      }
    };

    $(".bubble_action").each(function(){
      var self = $(this);
      var popup = $(".bubble_dialog").clone();
      self.hover(function(){
        self.append(popup);
        populate_nav_popup(popup, self);
        popup.css({"top": "52px"}).animate({"top": "-=10px"}, "fast").show();
      }, function(){
        popup.remove();
      });
    });

/* Search AutoComplete
--------------------------------------  */
    var auto_complete_called = 0;
    var auto_complete_selection;

    function auto_complete_lookup(div) {
      if(!auto_complete_called) {
        auto_complete_called = 1;
        setTimeout(function() {
          auto_complete_lookup_inner(div);
          auto_complete_called = 0;
        }, 200);
      }
    }

    function auto_complete_lookup_inner(div) {
      auto_complete_called++;
      var input = div.find('input').attr('value');
      $.get("/products/auto_complete", {
        queryString: input
      }, function(data) {
        var list = div.find('ul');
        list.parent().show();
        list.html(data.html);
        list.css('display', 'block');

        list.jScrollPane({ dragMinHeight:10, scrollbarWidth:10 });
        list.parent().addClass('dropdown');
        auto_complete_selection = -1;
        if (data.html.length === 0) {
          list.parent().hide();
        }
      });
    }

      $('.auto_complete input').focus(function(){
        if ($(this).hasClass("active")) {
          return;
        } else {
          $(this).val("");
          $(this).addClass("active");
        }
      });
      $('.auto_complete div').hide();
      $('.auto_complete input').bind('keydown', function(e){
        var div = $(".auto_complete");
        var list = $('.auto_complete ul');
        var items = list.children();
        var auto_complete_count = items.size();
        var key = e.charCode || e.keyCode || 0;
        switch (key){

          //down arrow 40
          case 40:
            if((auto_complete_count - 1) == auto_complete_selection){ auto_complete_selection = -1; }
            auto_complete_selection++;
            fill(list);
            break;

          //up arrow 38
          case 38:
            if(auto_complete_selection <= 0){ auto_complete_selection = (auto_complete_count - 1);
            } else { auto_complete_selection--; }
            fill(list);
            break;

          case 27:
            list.hide();
            break;

          case 37:
            break;

          case 39:
            break;

          case 13:
            break;
          default:
            auto_complete_selection = -1;
            auto_complete_lookup(div);
            break;
        }
      }
    );

    function fill(list){
      var items = list.children();
      var item = items.eq(auto_complete_selection);
      fill_inner(item);
      var top_bounds = list.parent().offset().top;
      var bottom_bounds = top_bounds + list.parent().height();
      if(item.offset().top < top_bounds || item.offset().top > bottom_bounds ){
        list[0].scrollTo('.highlight');
      }
    }

    function fill_inner(item){
      item.parent().children().removeClass('highlight');
      item.addClass('highlight');
      $('.auto_complete input').val(item.attr('fill'));
      return false;
    }

    $(".jScrollPaneContainer li").live("click",function(){
      fill_inner($(this));
      $(this).parents('form').submit();
      hide_autocomplete();
      return false;
    });

    $(".jScrollPaneContainer li").live("mouseover",function(){
      auto_complete_selection = $(this).attr('idx');
      fill_inner($(this));
    }, function(){
      $(this).removeClass('highlight');
    });


    $('body').unbind('click').click(function(e) {
       hide_autocomplete();

    });

    var hide_autocomplete = function() {
      $(".auto_complete .jScrollPaneContainer").hide();
    };

		   /*
		Product Search
		======================================  */

		$('.sizes_flyout').live('click', function() {
      var $this = $(this), $main = $('#main_wrapper'), $parent = $this.parent().parent();
      $('.dialog').remove();
      $.get('/products/sizes_types/' + $parent.metadata().id, null, function(r) {
        var $dlg = $(r);
        $dlg.find('a.list_item').click(function() {
          $.get(this.href, null, function(response) {
            var $html = $(response.html);
            $parent.replaceWith($html);
            $html.effect('highlight');
            $parent = $html;
          }, "json");
          return false;
        });
        $main.append($dlg);
        center($dlg);
        $dlg.css({ top: $this.offset().top + 29 }).fadeIn('slow');
      }, 'html');
		  return false;
		});

		$('.close_it').live('click', function() {
		  $(this).parents('.dialog').remove();
		  return false;
		});

		refresh_order = function(response){
			$("#order_column .items").empty().html(response.order_items).hide().fadeIn('fast');
		};


/*  Frequency Nag
======================================*/
		$(document).bind("frequency::nag", function(evt, response) {
			$(document).trigger("cart::updated", response);
			refresh_order(response);
			$('#subscriptions').parent().remove();
			close_dialog();
			if (response.subscription_json.subscription) {
				var $dialog = $('.check_reorder_freq'),
				$mask = $('#overlay_white');
	      subscription = response.subscription_json.subscription;
				$dialog.find('#product_id_freq').val(subscription.product_id);
	      $dialog.find('#frequency').val(response.subscription_json.recommended_frequency);
        var actual_freq = null;
				if (response.subscription_json.actual_frequency <= 30) {
					actual_freq = "Every " + (parseInt(response.subscription_json.actual_frequency/7, 10) ) + " weeks";
				} else {
					actual_freq = "Every " + (parseInt(response.subscription_json.actual_frequency/30, 10) ) + " months";
				}
				$dialog.find('#item_frequency').html("Every " + ( parseInt(subscription.frequency/7, 10) ) + " weeks");
				$dialog.find('#actual_frequency').html(actual_freq);
				center($dialog);
				$mask.show();
				$dialog.fadeIn('slow');
			}
		});

		$('#no_thanks').live('click', function(){
        close_dialog();
    });

    close_dialog = function(){
        $dialog = $('#subscriptions.show, .ui-draggable, .alice-gen-popup, .check_reorder_freq, .popup');
        $mask = $('#overlay, #overlay_white');
        $dialog.fadeOut("slow");
        $mask.fadeOut("slow");
        return false;
    };

		center = function(dialog){
        dialog.css(ViewPort.center(dialog.width(), dialog.height()));
    };


/* Shelf Closed
====================================== */
	$(document).bind("shelf::deactivated", function(evt, response) {
    if(response) {
      $('.alice-gen-popup.thanks').remove();
      var $thanks = $(response.thanks);
      $thanks.find('.add_button').click(function() { $('.alice-gen-popup.thanks').remove(); });
      $('body').append($thanks);
      $(document).trigger("show::popup", ["thanks", response]);
      $(document).trigger("cart::updated", response);
    }
	});

/* Generic Popup
====================================== */

	$(document).bind("show::popup", function(evt, popup_name, response) {
		var $dialog = $(".alice-gen-popup." + popup_name);
		$('#shelf_flyout_wrapper, #subscriptions.show, .ui-draggable').hide();
		$('#overlay_white').show();
		$dialog.css({'margin-top': '-60px', 'margin-left': '-60px'});
		if (response && response.html) {
		  $dialog.find(".cnt").html(response.html);
		} else if (response && response.error) {
		  $dialog.find(".cnt").html(response.error);
		}
    center($dialog);
		$dialog.hide().fadeIn("slow");
		$dialog.find(".close_the_popup").live("click", function(){
			close_dialog();
			return false;
		});
	});

	$('.apply_gift_card_btn').click(function(){
	  $('#overlay_white').css("opacity", 0.5);
		$.ajax({
			url: '/checkout/show_gift_cards',
			success: function(response){
			  $(document).trigger("show::popup", ["gift_cards", response]);
			}
		});
		return false;
	});

	$(".gift_card_refresh").live('click', function(){
	  document.location.reload();
	  return false;
	});


/* Coupons
====================================== */
    $('.coupon_exists, .coupon').hover(
        function() {
            $(this).next('.coupon_popup').slideToggle('fast');
        },
        function() {
            $(this).next('.coupon_popup').slideToggle('fast');
        }
        );


/* Image Zoom
====================================== */
    $('img_zoom').draggable();
    $('.product_zoom').click(function() {
      var self = $(this), product_id = self.attr('id');
      $.ajax({ 
        url: '/products/fetch_product_zoom/'+product_id,
        data: { authenticity_token: AUTH_TOKEN },
        success: function(response) {
          var dialog = $('#img_zoom');
          $('#img_detail').html(response.img_zoom);
          dialog.hide().css(ViewPort.center(dialog.width(), dialog.height()));
          $('#overlay').show();
          dialog.show();
        }
      });
    });

    $('#close_img_zoom').live('click', function(){
        $(this).parents('#img_zoom').hide().find('#img_detail').empty();
        $('#overlay').hide();
    });

    /*
Utility
======================================  */
    ie6Overlay = function(mask) {
      var w = $(window);
      mask.css({ top: Math.round((w.height() - mask.height()) + w.scrollTop()) });
    };


    function truncate(str, len) {
        var out = str.substr(0, len);
        if (str.length > len){
            out+='...';
        }
        return out;
    }

    $('#product_suggestion_form').submit(function(){
        $.ajax({
            url: '/products/suggest_product',
            data: $(this).serialize(),
            success: function() {
                $('#product_suggestion_textarea').val("");
                $('#thanks_for_suggestion_title').show();
            }
        });
        return false;
    });


  // updates super shelves, after a coupon is shared on FB
  $(document).bind('alice::sharing_event', function(event, response) {

    // subscription shelf
    var subscriptionDialog = $('#subscriptions.show');
    var coupon_panel = $('#panel-coupon');
    var congrats = $('<h3></h3>');
    congrats.text(response.message);
    coupon_panel.find('.discount').text("$"+response.discount+' off');
    coupon_panel.find('.message').empty().append(congrats);
    coupon_panel.find('.share_bonus').empty();
    subscriptionDialog.find('#total_table .discount .coupon_impression').text("$"+response.discount);
    subscriptionDialog.find('#total_table .net .total').text('$'+response.net_price);

    /* product shelf (no subscription) */
    var coupon_info = alice.jQuery('#shelf_flyout .coupon_info');
    coupon_info.find('.discount').text('$'+response.discount+' off');
    coupon_info.find('.message').addClass('thanks');
    coupon_info.find('.message').empty().append(congrats);
    coupon_info.find('.share_bonus').empty();

    var footer = alice.jQuery('#shelf_flyout .footer');
    footer.find('.discount').text('$'+response.discount);
    footer.find('.total').text('$'+response.net_price);
    footer.find('.big.price').html('$'+response.net_price+'<span class="wc">w/ coupon</span>');
    return false;
  });

}); // $(document).ready

$(window).load(function(){

    $('.shelf .item img').each(function(){
        var item = $(this).parents('.item'),
        price = item.find('.price'),
        image = item.find('.product_image');
        if(item.width() > price.width()) {
            price.css({
                left: (item.width()-price.width())/2
            });
        } else {
            $(this).parents('.item').css({
                width: price.width(),
                textAlign: 'center'
            });
            image.css({
                'margin-left': (item.width()-image.width())/2,
                'margin-right': (item.width()-image.width())/2
            });
        }
    });

    $('.shelf .item .show_status').each(function(){
      update_show_status_css($(this));
    });
});

function update_show_status_css(div) {
  var item = div.parents('.item');
  var image = item.find('img');
  var link = item.find('a');
  div.css({ 'margin-left': (image.width()-div.width())/2 });
  if ($.browser.msie) {
    if($.browser.version.substr(0,1) == '6') {
      div.css({ 'margin-top':  93 });
      var offset = 65;
      if(item.width() > div.width()) { offset = 80; }
      var ml = div.css('margin-left');
      ml = parseInt(ml.substr(0, ml.indexOf('px')), 10) - offset;
      div.css({ 'margin-left':  ml + 25 });
    } else if($.browser.version.substr(0,1) == '7') {
      div.css({ 'margin-top':  134 });
      var mll = image.width();
      div.css({ 'margin-left':  -mll - 20 });
    }
  } else if(!$.browser.msie) {
    div.css({ 'margin-top':  3 });
  }
  div.css('display', 'block');
}

var addGiftCard = function() {
  var $error = $('#pc_error');
  $error.empty();
  var cod = $('#pc1').val() + $('#pc2').val() + $('#pc3').val();
  if (cod.length != 15) {
    $error.html('Please enter all 15 digits from the back of your gift card.');
  } else {
    var tkn = $('#authenticity_token').val();
    var $dialog = $('#gift_card_wrapper');
    $('#btn').hide();
    $('#wait').show();
    $.ajax({
      url: '/checkout/add_gift_card',
      data: { authenticity_token: tkn, code: cod },
      success: function(response) {
        $('#wait').hide();
        $('#btn').show();
        if (response.success) {
          $('.gift-cnt').html(response.html);
        } else {
          $error.html(response.error);
        }
      }
    });
  }
};

/* simply stop non-search queries */
$('#search > form').submit(function() {
  var search_box = $('#search_text > input')[0];
  var input_val = search_box.value;
  if (input_val === 'Search for products...' || input_val === '' || !input_val) {
    search_box.focus();
    return false;
  }
  return true;
});

function clk(l, type, cid) {
  if (document.images) {
    var now = new Date().getTime();
    (new Image()).src= '/clk/' + type + '/' + cid + '.gif?' + now;
  }
  return true;
}
