Amara = {};

/**
 * Misc jQuery stuff
 */
(function($) {
	/**
	 * Timed input observer
	 *
	 * Modified version of:
	 *
	 * https://github.com/splendeo/jquery.observe_field/blob/master/jquery.observe_field.js
	 */
	$.fn.observeRadio = function(frequency, callback) {
		frequency = frequency * 1000; // translate to milliseconds

		return this.each(function(){
			var $this = $(this);
			var previousVal = $this.is(':checked');

			var check = function() {
				var val = $this.is(':checked');
				if(previousVal != val){
					previousVal = val;
					$this.map(callback); // invokes the callback on $this
				}
			};

			check();
			setInterval(check, frequency);
		});
	};

	/**
	 * Attach add-to-bag action to the given elements
	 */
	$.fn.emptyInputOnEnter = function($url, options) {
		return this.each(function() {
			var originalValue = this.value;

			$(this).focus(function (evt) {
				if (this.value == originalValue) {
					this.value = "";
				}
			}).blur(function (evt) {
				if (this.value == '') {
					this.value = originalValue;
				}
			});
		});
	};

	/**
	 * Stop selection on click of the back/next
	 * http://chris-barr.com/index.php/entry/disable_text_selection_with_jquery/
	 */
	$.fn.disableTextSelect = function() {
		return this.each(function() {
			if($.browser.mozilla) {//Firefox
				$(this).css('MozUserSelect','none');
			} else if($.browser.msie) {//IE
				$(this).bind('selectstart',function(){return false;});
			} else {
				// Opera, webkit etc.
				$(this).mousedown(function(){return false;});
			}
		});
	};
})(jQuery);

/**
 * Amara help box
 * 
 * Adds the help box html into the div#minimised-tabs element
 */
(function($) {
	var $dialog = false;
	var $content = false;
	var $url = false;
	
	var init = function () {
		if ($dialog) {
			return;
		}
		$dialog = $("#help-box").dialog({
			autoOpen: false,
			dialogClass: "stalker-box",
			resizable: false,
			width: 460,
			minHeight: 250,
			show: 'slide',
			close: function () {
				// Track close
				track('Close');
			}
		});

		// Create help box content div and load content from server
		$content = $("<div>One moment please...</div>");
		$content.load($url);
	};
	
	// Track via google analytics
	var track = function (label) {
		if (typeof _gaq !== 'undefined') {
			_gaq.push(['_trackEvent', 'Buttons', 'Helpbox', label]);
		}
	}
	
	// Toggle open/close of the dialog
	var toggle = function () {
		init();
		
		if ($dialog.dialog('isOpen')) {
			$("#help-box").dialog("close");
			// Close is tracked on the dialog event listener
		} else {
			$("#help-box").dialog("open");
			$("#help-box").html($content);
			
			// Hack alert!
			// todo: refactor this into some dialog manager
			if ($("#stalker-box").stalkerBoxClose) {
				$("#stalker-box").stalkerBoxClose();
			}
			
			track('Open');
		}
	};

	$.fn.amaraHelpBox = function(url, options) {
		$('#minimised-tabs').append('<div id="help-box-minimised" class="help-box-minimised"></div>');
		$("#help-box-minimised").click(toggle);
		$url = url;

		return this;
	};
	
	// Close the currently open help box
	$.fn.amaraHelpBoxClose = function() {
		if ($dialog && $dialog.dialog('isOpen')) {
			toggle();
		}

		return this;
	};
	
})(jQuery);

/**
 * Amara add to bag
 */
(function($) {
	var showWorking = function (statusEl) {
		$(statusEl).addClass('ajax-status-working');
	};
	var showFail = function (statusEl, message) {
		$(statusEl).removeClass('ajax-status-working');
		$.achtung({message: message, timeout:8, 'className' : 'achtungFail'});
	};
	var showSuccess = function (statusEl, quantity, productName) {
		$(statusEl).removeClass('ajax-status-working');

		var message = '' + quantity + 'x ' + productName + ' added to your bag';

		$.achtung({message: message, timeout:5, 'className' : 'achtungSuccess'});
	};

	var doAddToBag = function ($url, options) {
		var slug = $(options.slugEl).val(),
			quantity = $(options.quantityEl).val(),
			statusEl = options.statusEl,
			showSuccess = options.showSuccess
		;

		showWorking(statusEl);

		var data = {
			slug: slug,
			quantity: quantity
		};

		$.getJSON($url, data, function (response) {
			if (response) {
				if (response.quantity > 0) {
					// Update quickcart content
					$('#quick-basket').html(response.quickCartHtml);

					// Update count
					$('#header-cart-item-count').html('(' + response.cartItemCount + ')');

					// Show checkout button
					$('#header-cart-checkout').show();
					
					showSuccess(statusEl, response.quantity, response.productName);
					if (response.message) {
						// We had some sort of error message too, probably
						// something about last stock!
						showFail(statusEl, response.message);
					}
				} else {
					if (response.redirect && response.redirect.length > 0) {
						window.location = response.redirect;
					} else {
						showFail(statusEl, response.message);
					}
				}
			} else {
				showFail(statusEl, "Please try again");
			}
		});
	};

	/**
	 * Attach add-to-bag action to the given elements
	 */
	$.fn.attachAddToBag = function($url, options) {
		options = $.extend( {
			statusEl: null,
			slugEl: null,
			quantityEl: null,
			quickBagAlert: false,
			showSuccess: showSuccess
		}, options || {});

		return this.each(function() {
			var button = this;

			$(button).click(function (evt) {
				evt.preventDefault();
				doAddToBag($url, options);
			});
		});
	};
	
})(jQuery);


/**
 * Amara quick bag
 */
(function($) {
	$.fn.amaraQuickBag = function(options)
	{
		var isMethodCall = (typeof options === 'string'),
			args = Array.prototype.slice.call(arguments, 0),
			name = 'amaraQuickBag';

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// prevent calls to internal methods
			if (isMethodCall && options.substring(0, 1) === '_') {
				return this;
			}

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $.amaraQuickBag(this))._init(args));

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args.slice(1)));
		});
	};

	$.amaraQuickBag = function(element)
	{
		var args = Array.prototype.slice.call(arguments, 0), $el;

		if (!element || !element.nodeType) {
			$el = $('<div />');
			return $el.amaraQuickBag.apply($el, args);
		}

		this.$container = $(element);
	};

	/**
	 * Static members
	 **/
	$.extend($.amaraQuickBag, {
		version: '1.1.0',
		defaults: {
			className: ''
		}
	});

	/**
	 * Non-static members
	 **/
	$.extend($.amaraQuickBag.prototype, {
		$container: false,
		mouseOn: false,
		options: {},

		_init: function(args)
		{
			var o, self = this;

			args = $.isArray(args) ? args : [];
			args.unshift($.amaraQuickBag.defaults);
			args.unshift({});

			o = this.options = $.extend.apply($, args);

			$(o.opener).hoverIntent({
				over: function () {
					self.open();
				},
				out: function () {}
			});

			$(o.opener).mouseenter(function () {
				self.mouseOn = true;
			});

			$(o.opener).mouseleave(function () {
				self.mouseOn = false;
				self.close();
			});
		},

		open: function () {
			$(this.$container).show();
		},

		/**
		 * Alert the customer to a change n their cart
		 */
		alert: function () {
			var self = this;
			$(this.$container).slideDown('slow', function() {
				// Close in a couple of seconds if the user's mouse is out
				setTimeout(function () {self._closeNow()}, 4000);
			});
		},

		close: function () {
			var self = this;
			setTimeout(function () {self._closeNow()}, 1000);
		},

		_closeNow: function () {
			if (!this.mouseOn) {
				$(this.$container).slideUp('slow');
			}
		}
	});

})(jQuery);


/* Hacked for bgiframe ie9 fix!
 *
 * Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 18:45:56 -0500 (Sat, 21 Jul 2007) $
 * $Rev: 2447 $
 *
 * Version 2.1.1
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie && parseInt($.browser.version) === 6){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);

