/*
 *
 * Copyright (c) 2009 Doubleclique (dev [at] doubleclique [dot] com)
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license
 *
 */

/**
 *
 * jquery.dql.filtermenu
 *
 * @name     jquery.dql.filtermenu
 * @version  0.1
 * @author   Kyle Beattie (kyle [at] doubleclique [dot] com)
 * @requires jQuery
 *
 */
/*global jQuery */
"use strict";
(function ($) {

	$.fn.cellar = function (options) {

		var $this = $(this), priv = {}, publ = {};

		options = $.extend(
			{
				counters : $('.badge, .cellarCount')
			},
			options
		);

		priv.init = function () {

			priv.cellarCount = '';
			
			priv.addEventHandlers();

		};

		priv.addEventHandlers = function () {

			$this.submit(function (event) {

				event.preventDefault();

				$this.find('input[type="submit"]').blur();

				var action = $this.attr('action');

				var val = $this.find('select').val();

				$this.addClass('loading');

				// Use $.ajax to get update value
				setTimeout(function () {

					priv.updateCellarCount(val);

					priv.cellarCount = val;
					
				},1000)
				
				//
//				$.ajax({
//					url : action,
//					success : function (data) {
//
//						priv.updateCellarCount(val); // should be value returned
//
//						priv.cellarCount = val; // should be value returned
//					}
//				});
				
			});

		};

		priv.updateCellarCount = function (val) {

			options.counters.each( function (index) {

				if (index == 0) {

					var oldNum = $(this).text();
					
					var num = val < 10 ? '0' + val : val;
					
					var numElement = $('<span></span>').text(oldNum);

					$(this).html(numElement);

					numElement.animate({
						opacity : 0
					}, 200, "linear", function() {

						numElement.text(num);

						numElement.animate({
							opacity : 1
						});
					});

				} else {

					$(this).text(val);

				}

			});
			
			$this.removeClass('loading');
			
		};

		priv.init();

		return publ;

	}

}(jQuery));
