var MISSION = {
	common : {
		init : function() {
			$('form').submit(MISSION.common.validateForm);
			$.standardize();

			/* Recipe Search
			===========================================================================*/
			// Recipe list page works differently than normal search
			var func;
			// if ($('body').attr('class').indexOf('recipeList') != -1) {
			//		func = MISSION.recipeList.tokenizeSearch;
			// } else {
				func = MISSION.recipeLanding.submitQuickSearch;
			// }


			// TODO: This all needs to be refactored to fit within model
			$('.sortList').change(function() {
				$('#reSort').val($(this).val());
				$('#alterFacet').submit();
			});
			// end refactor

			$('form.quickSearch input')
				.keyup(function() {
					if ($.browser.msie && $.browser.version == 6) {
						$els = $('form.recipeSelector select');
						if ($('div.ac_results').is(':visible')) {
							$els.hide();
						} else {
							$els.show();
						}
					}
				}).autocomplete("/cookbook/auto.php", {matchContains: true}).result(func);

			$('form.quickSearch a.submit').click(func);
			$('button.saveRecipe').one('click', MISSION.common.addToBox);
		},	// end common.init()

		addToBox : function() {
			var $button = $(this);
			var data = $(this).attr('data-recipeId');
			var url = '/cookbook/buildyourown/index.php?n=recipes&a=ajaxTarget&d=0&named[saveRecipe]=' + data;
			$.ajax({
				url : url,
				success : function(str) {
					if (str.indexOf('errormsg') === -1) {
						$button.find('img').attr('src','/cookbook/img/recipe-list/saved-btn.png');
						$button.unbind();
					} else {
						if (str.indexOf('logged in') !== -1) {
							UTIL.log("guess i'm not loggedin response str from url");
							UTIL.log(url);
							UTIL.log(str);
							window.location = '/cookbook/buildyourown/index.php?n=users&a=login&fromRecipeId=' + data;
						}
					}
				}
			});
		},	// end addToBox()

		setRecipeState : function() {
			// Set recipe saved state
			var $buttons = $('button.saveRecipe');
			$.ajax({
				url: '/cookbook/buildyourown/index.php?n=recipes&a=jindex&d=0&named[content_type]=json&named[data]=ids',
				success: function(str) {
					var data = [];
					data = str.split(',');
					for (var i = 0; i < data.length; i++) {
						var id = data.pop();
						$buttons.each(function() {
							if ($(this).attr('data-recipeid') == id) {
								$(this).addClass('saved').unbind().find('img').attr('src', '/cookbook/img/recipe-list/saved-btn.png');
							}
						});
					}

					$buttons.show();
				},
				error: function() {
					alert('request failed!');
				}
			});
		},	// end setRecipeState()

		validateForm : function() {
			var $form = $(this);
			var errorStr = '';

			$('.field.error').removeClass('error');

			$form.find('input.required').each(function() {
				var $el = $(this);
				var val = $el.val();

				if ($el.hasClass('email')) {
					var pos = val.lastIndexOf("@");
					if (!(pos > 0 && (val.lastIndexOf(".") > pos) && (val.length - pos > 4))) {
						$el.parent('.field').addClass('error');
						errorStr += "Please enter a valid email address\n";
					}

				} else if ($el.attr('id') === "UserPassword") {
					if (!val) {
						$el.parent('.field').addClass('error');
						errorStr += "Please enter your password\n";
					}

				} else if ($el.attr('id') === "UserRetypePassword") {
					if ($('#UserPassword').val() != $el.val()) {
						$el.parent('.field').addClass('error');
						errorStr += "Passwords do not match\n";
					}

				} else if ($el.hasClass('text')) {
					if (!val || val.length === 0) {
						$el.parent('.field').addClass('error');
						errorStr += "Please enter a value for " + $el.prev('label').text() + "\n";
					}
				}
			});

			if (errorStr) {
				return false;
			} else {
				return true;
			}
		},	// end validateForm()

		finalize : function() {
			$('form.rating').show();
		}
	},	// end MISSION.common

	recipeLanding : {
		init : function() {
			/* Main Recipe Scroller
			===========================================================================*/
			var api = $('div.scrollable')
				.scrollable({circular: true})
				.autoscroll(
					{
						autoplay: true,
						interval: 5000
					}
				)
				.navigator()
				.data('scrollable');

			$('.navi a').click(function() {
				api.stop();
			});

			/* Recipe Select
			===========================================================================*/
			var $buttons = $('form.recipeSelector button');
			$buttons
				.hover(MISSION.recipeLanding.toggleButtonImage)
				.click(MISSION.recipeLanding.submitRecipeSelector);

		},	// end MISSION.recipeLanding.init

		submitQuickSearch : function() {
			if ($('input[name="search"]').val() == "Ingredient, Product, etc.") {
				return false;
			} else {
				$(this).closest('form').submit();
			}
		},

		submitRecipeSelector : function() {
			var time = $(this).attr("data-duration");
			$('input[name="duration"]').val(time);
		},

		toggleButtonImage : function() {
			var $img = $(this).find('img');
			var src = $img.attr('src');

			if (src.indexOf('-on.png') == -1) {
				$img.attr('src',src.replace('.png','-on.png'));
			} else {
				$img.attr('src',src.replace('-on',''));
			}
		}
	},	// end MISSION.recipeLanding

	recipeList : {
		init : function() {
			$('a.clear').click(MISSION.recipeList.clearAllOptions);
			$('a.facetChanger').click(MISSION.recipeList.updateSearchParams);
			$('a.rmSelectedFacet').click(MISSION.recipeList.rmSearchParams);

			MISSION.common.setRecipeState();
		},	// end recipeList.init()

		rmSearchParams : function() {
			//just in case this is the collection one, which uses funky pluses
			var myfacetvalue=$(this).attr("data-facetvalue");
			if (myfacetvalue.indexOf("+")) {
				myfacetvalue = "\""+myfacetvalue.replace(/\+/," ",myfacetvalue)+"\"";
			}
			$("#rmFacetField").val($(this).attr("data-facetfield"));
			//$("#rmFacetValue").val($(this).attr("data-facetvalue"));
			$("#rmFacetValue").val(myfacetvalue);
			$("#addFacetField").val('');
			$("#addFacetValue").val('');

			UTIL.log($("#rmFacetValue").val());
			UTIL.log($("#rmFacetValue").val());
			$("#alterFacet").submit();
			return false;
		},
		updateSearchParams : function() {
			$("#addFacetField").val($(this).attr("data-facetfield"));
			$("#addFacetValue").val($(this).attr("data-facetvalue"));
			$("#rmFacetField").val('');
			$("#rmFacetValue").val('');

			UTIL.log($("#addFacetValue").val());
			UTIL.log($("#addFacetField").val());
			$("#alterFacet").submit();
			return false;
		},	// end updateSearchParams()

		clearAllOptions : function() {
			$('div.filterSet input:checked').removeAttr('checked');
			return false;
		},	// end clearAllOptions()

		tokenizeSearch : function(event, data, formatted) {
			var tokenWrapper = $('<li class="token-input-token"/>');

			var token = $('<p/>', {
				text : data[0]
			}).appendTo(tokenWrapper);

			var closeBtn = $('<span/>', {
				"class" : "token-input-delete-token",
				text : "x",
				click: function() {
					$(this).closest('li').remove();
				}
			}).appendTo(tokenWrapper);

			tokenWrapper.appendTo('ul.token-input-list');

			$('form.quickSearch input').val('').blur();
		}	// end tokenizeSearch()
	},	// end MISSION.recipeList

	recipeDetail : {
		init : function() {
			$('form.rating div.star-rating-live a').live('click', MISSION.recipeDetail.rateRecipe);

			MISSION.common.setRecipeState();

			var api = $('ul.tabs').tabs('div.panes > div', {
				tabs: 'li'
			}).data('tabs');
			api.onClick(function(index) {
				var tmp = api.getConf();
			});

			$('a.hasTooltip').tooltip({
				delay: 100,
				effect: 'fade',
				position: 'center right',
				offset: [42,15]
			});
		},	// end recipeDetail.init()

		rateRecipe : function() {
			var $form = $(this).closest('form');
			var recipeId = $form.find('#recipeId').val();
			var rating = $(this).attr('title');

//			var url = '/cookbook/ajaxHandler.php';
var url = '/cookbook/buildyourown/index.php?';
			var getData = 'n=recipes&a=saveRating&id='+recipeId +'&rating='+rating;
//'rating=' + rating + '&recipeId=' + recipeId;
			// getData += "&dc=1";
//			UTIL.log(url+'?'+getData);
//return false;
			$.ajax({
				type: 'GET',
				url: url,
				data: getData,
				success: function(data) {
					if (data == 'dupe') {
						alert('You have already rated this recipe. Thank you.');
						return false;
					} else if (data == 'updated') {
						// alert('Thank you for rating this recipe.')
					} else {
						UTIL.log(data);
					}
				},
				error: function(data) {
					UTIL.log('error saving rating' + data);
				}
			});

			// Increment numRatings on client side
			var $span = $form.find('span.numRatings');
			var numRatings = parseInt($span.text().slice(1,-1));
			numRatings++;
			numRatings = numRatings.toString();

			$span.text("(" + numRatings + ")");
		}	// end rateRecipe()
	},	// end MISSION.recipeDetail

	recipeBox : {
		init : function() {
			MISSION.recipeBox.initModal();

			$('img[data-coverId]').click(MISSION.recipeBox.selectCover);
			$('li.remove a').click(MISSION.recipeBox.removeFromBox);
			$('a.sort').click(MISSION.recipeBox.sortRecipes);

		},	// end recipeBox.init()

		removeFromBox : function() {
			var $recipe = $(this).closest('li.recipeOverview');
			$recipe.fadeOut('slow', function() {
				var id = $(this).attr('data-id');
				var url = '/cookbook/buildyourown/index.php?n=recipes&a=ajaxTarget&d=0&named[deleteRecipe]=' + id;
				$.ajax({
					url: url,
					success: function() {
						$(this).remove();
					}
				});
			});
			return false;
		},	// end removeFromBox()

		sortRecipes : function() {
			$('form.sortForm').addClass('activated');
			$('ul.sortable').sortable({
				axis: 'y',
				placeholder: 'highlight',
				update: function(event, ui) {
					var i = 1;
					$('ul.sortable input[type="hidden"]').each(function() {
						$(this).val(i);
						i++;
					});
				}
			}).disableSelection();
			return false;
		},	// end sortRecipes()

		selectCover : function() {
			var $li = $(this).parent();
			$li.siblings().removeClass('selected');
			$li.addClass('selected');

			var id = $(this).attr('data-coverId');
			$('#selectedCover').val(id);
		},	// end selectCover()

		initModal : function() {
			var modified = false;
			$('.modal[rel="#modal"]').overlay({
				close: 'a.close',
				closeOnClick: false,
				mask: {
					color: '#000',
					opacity: 0.7
				},
				onBeforeClose: function() {
					if (modified) {
						window.location = "/cookbook/buildyourown/index.php?n=recipes&a=table";
					}
				}
			});
			$('#modal.create form').submit(function() {
				if ($(this).has('p.error').length) {
					return false;
				}
				var data=$(this).serialize();
				var url = '/cookbook/buildyourown/index.php?n=recipes&a=ajaxTarget&d=0&named[generateCookbook]=' + $('#UserId').val();
				$.ajax({
					type : "GET",
					url : url,
					data : data,
					success : function(msg) {
						$('.newTitle').text($('#UserCookbookTitle').val());
						var cover = $('#selectedCover').val();
						var coverStr = '/cookbook/img/cookbook-covers/' + cover + '.jpg';
						$('.newCover').attr('src', coverStr);

						$('div.step2').hide();
						$('div.step3').show();
						modified = true;
					}
				});

				$('div.step1').hide();
				$('div.step2').show();

				return false;
			});

			$('#UserCookbookUrl').blur(function() {
				var $el = $(this);
				var url = '/cookbook/buildyourown/index.php?n=users&a=ajaxTarget&d=0&named[uniqueUrl]=' + $(this).val();
				$.ajax({
					url: url,
					success: function(data) {
						if(data.indexOf('errormsg') != -1) {
							$el.prevAll('p').find('em').text('This URL has already been taken. Please try another one.').addClass('error');
						} else {            
							$el.prevAll('p').find('em').text('Give your cookbook a unique URL that you can share with your friends!').removeClass('error');
						}
					}
				});
			});

			$('a.popup').click(function() {
			var str = "/cookbook/user/"+$("#UserCookbookUrl").val();
				var newWindow=window.open(str,'name','width=1020,height=700');
//				var newWindow = window.open('/cookbook/buildyourown/index.php?n=recipes&a=getByName','name','width=1020,height=700');
				if (window.focus) {
					newWindow.focus();
				}
				window.location = "/cookbook/buildyourown/index.php?n=recipes&a=table";
				return false;
			});
		}	// end initModal()
	}	// end MISSION.recipeBox
};

/*===========================================================================
	Utilities
===========================================================================*/
// Standardize common HTML5 functionality across browsers
(function($) {
	$.standardize = function() {
		function init() {
			if (!Modernizr.input.placeholder) {
				addPlaceholders();
			}

			// Prevent image flicker in IE
			if ($.browser.msie) {
				try {
					document.execCommand("BackgroundImageCache", false, true);
				}
				catch(e) {}
			}
		}

		function addPlaceholders() {
			$('input[placeholder]').each(function() {
				var $el = $(this);
				var str = $el.attr('placeholder');

				if ($el.val() === '') {
					$el.val(str);
				}

				$el.focus(function() {
					if ($el.val() === str) {
						$el.val('');
					}
				}).blur(function() {
					if ($el.val() === '') {
						$el.val(str);
					}
				});
			});
		}
		init();
	};
})(jQuery);

var UTIL = {
	fire : function(func,funcname, args) {
		var namespace = MISSION;  // obj literal namespace

		funcname = (funcname === undefined) ? 'init' : funcname;

		if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function') {
			namespace[func][funcname](args);
		}
	},

	loadEvents : function() {
		var bodyId = document.body.id;

		UTIL.fire('common');

		$.each(document.body.className.split(/\s+/),function(i,classnm) {
			UTIL.fire(classnm);
			UTIL.fire(classnm,bodyId);
		});

		UTIL.fire('common','finalize');
	},

	log : function(msg) {
		if (window.console && window.console.log) {
			console.log(msg);
		}
	}
};

jQuery(document).ready(UTIL.loadEvents);

