$(document).ready(function() {
	if ($('#notifications span').length > 0) {
		$('#notifications span').each(function() {
			notify($(this).text());
		})
	}
	if (!$.cookie('nimble')) {
		$('body').append('<div class="warning" id="cookie_warning">It looks like you don\'t have cookies enabled. You\'ll need to enable them to place an order.</div>');
	}
	$('.contact_product').each(function() {
		var id = $(this).attr('id').split('-')[1];
		$(this).attr('href', $(this).attr('href') + '?product=' + id);
	});
	$('#login_link').each(function() {
		$(this).attr('href', $(this).attr('href') + '?' + window.location.pathname);
	});
	$('input#q').hint();
	$('input#search').click(function(e) {
		$('#search_form').submit();
		e.preventDefault();
	});
	$('input, textarea').focus(function() {
		$(this).addClass('active');
	});
	$('input, textarea').blur(function() {
		$(this).removeClass('active');
	});
	// TODO: Make me a plugin
	$('input.tip, textarea.tip').blur(function() {
		var o = $(this);
		var tip = $('#input_tip');
		o.attr('title', tip.text());
		$('#input_tip').remove();
	});
	$('input.tip, textarea.tip').focus(function() {
		var o = $(this);
		var top = o.offset().top;
		var left = o.offset().left;
		var width = o.width();
		var tip_text = o.attr('title');
		o.attr('title', '');
		var msgbox = '<div id="input_tip">';
		msgbox = msgbox + '<div class="msg_box_top"><div><div></div></div></div>';
		msgbox = msgbox + '<div class="msg_box"><div><div>' + tip_text + '</div></div></div>';
		msgbox = msgbox + '<div class="msg_box_bot"><div><div></div></div></div></div>';
		$('body').append(msgbox);
		var tip = $('#input_tip');
		tip.css('top', top - tip.height() + 35);
		tip.css('left', left + width + 3);
	});
	$('input.required, textarea.required, select.required').each(function() {
		$('label', $(this).parent()).addClass('required');
	});
	$('a.buyit').click(function(e) {
		var o = $(this);
		o.blur();
		var product = o.attr('id').split('-')[1];
		var title = o.parent().siblings('a').text();
		add_to_cart(product, title);
		e.preventDefault();
	});
});

function notify(text) {
	$('#feedback div').css('background-image', 'url(' + STATIC + 'icons/32x32/ok.png)');
	$('#feedback span').fadeOut('fast', function() {
		$(this).empty().append(text).fadeIn();
	});
	$('#feedback').fadeIn(400);
	$('#feedback').animate({opacity: 0.95}, 3500, function() {
		$('#feedback').fadeOut(1200);
	});
}

function loading(text) {
	busy();
	$('#feedback div').css('background-image', 'url(' + STATIC + 'i/spinner_bigb.gif)');
	$('#feedback span').fadeOut('fast', function() {
		$(this).empty().append(text).fadeIn();
	});
	$('#feedback').fadeIn(400);
}
function done(text, success) {
	success = typeof(success) != 'undefined' ? success : true;
	var icon = '';
	busy(false);
	if (success) {
		icon = 'ok';
	} else {
		icon = 'error';
	}
	$('#feedback div').fadeOut('fast', function() {
		var d = $(this);
		d.css('background-image', 'url(' + STATIC + 'icons/32x32/' + icon + '.png)');
		$('#feedback span').empty().append(text);
		d.fadeIn('fast');
	});
	$('#feedback').animate({opacity: 0.95}, 2000, function() {
		$('#feedback').fadeOut(1200);
	});
}
function warning(text) {
	$('#feedback div').css('background-image', 'url(' + STATIC + 'icons/32x32/warning.png)');
	$('#feedback span').fadeOut('fast', function() {
		$(this).empty().append(text).fadeIn();
	});
	$('#feedback').fadeIn(400).animate({opacity: 0.95}, 4000, function() {
		$('#feedback').fadeOut(1200);
	});
}

function busy(busy) {
	busy = typeof(busy) != 'undefined' ? busy : true;

	if (busy) {
		$('body, .clickable').css('cursor', 'wait');
// 		$('body, .clickable').css('cursor', 'url(' + STATIC + 'i/spinner.gif)');
	} else {
		$('body').css('cursor', 'auto');
		$('.clickable').css('cursor', 'pointer');
	}
}

function add_to_cart(product, title, options) {
	options = typeof(options) != 'undefined' ? options : false;
	title = $.trim(title);
	loading('Adding "' + title + '" to your cart...');
	busy();
	var data = {'add_product': product, 'milk_token': milk_token};
	if (options) {
		for (var option in options) {
			data[option] = options[option];
		}
	}
	$.ajax({
		url: '/cart/',
		type: 'POST',
		data: data,
		success: function(ret) {
			update_minicart(ret);
			done('"' + title + '" was added to your cart');
		},
		error: function() {
			done("We're really sorry, there was a problem adding the product to your cart");
		}
	});
}

function update_minicart(items) {
	number = Number(items);
	if ($('#minicart span').length === 0) {
		$('#minicart')
		.after('<a href="/checkout/"><img src="' + STATIC + 'i/checkout.png" id="minicart_checkout" /></a>');
		$('#minicart_checkout').click(function() {
			window.location.href = '/checkout/';
		});
	}
	if (number === 0) {
		$('#minicart').hide('normal', function() {
			$(this).empty()
			.append('Your cart is currently empty').show('normal');
			$('#minicart_checkout').hide('slow');
		});
	} else if (number == 1) {
		$('#minicart').hide('normal', function() {
			$(this).empty()
			.append('<a href="/cart/">There\'s <span>' + number + '</span> item in your cart</a>').show('normal');
		});
	} else {
		$('#minicart').hide('normal', function() {
			$(this).empty()
			.append('<a href="/cart/">There\'s <span>' + number + '</span> items in your cart</a>').show('normal');
		});
	}
}

function valid_phone(str) {
	if (str.match(/^\+?[0-9\-() ]{7,}$/)) {
		return true;
	}
	return false;
}

function valid_email(str) {
	// /^.+@[^.].+\.[0-9a-z]{2,4}$/i
	if (str.match(/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+@([-0-9A-Z]+\.)+([0-9A-Z]){2,4}$/i)) {
		return true;
	}
	return false;
}

/* http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/ */
(function ($) {
$.fn.hint = function (blurClass) {
	if (!blurClass) blurClass = 'blur';
	return this.each(function () {
		var $$ = $(this);
		var title = $$.attr('title');
		if (title) {
			$$.blur(function () {
				if ($$.val() === '') {
					$$.val(title).addClass(blurClass);
				}
			})
			.focus(function () {
				if ($$.val() == title) {
					$$.val('').removeClass(blurClass);
				}
			})
			.parents('form:first').submit(function () {
				if ($$.val() == title) {
					$$.val('').removeClass(blurClass);
				}
			}).end()
			.blur();
			if ($.browser.mozilla && !$$.attr('autocomplete')) {
				setTimeout(function () {
					if ($$.val() == title) $$.val('');
					$$.blur();
				}, 10);
			}
		}
	});
};
})(jQuery);
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString();
		}
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
