$(document).ready(function() {
	
	// AJAX product lookup
	$("select#ProductID_2").change(function(){
		$("select#ProductID_1").empty();
		$("select#ProductID_1").addOption("", "Loading Products...", false);
		if (!$('#ProductFlavor').is(':visible'))
				$('#ProductFlavor').slideDown();
		var curProduct = $(this).val();
		if (curProduct.length != 0) {
			$.getJSON("searchResults.cfm",{doAction: 'lookupProductBranch', productid: curProduct}, function(j){
			  // Populate the dropdown
			  var options = '';
				$("select#ProductID_1").empty();
					$("select#ProductID_1").addOption('', 'Any Flavor', false);
			  for (var i = 0; i < j.length; i++) {
						$("select#ProductID_1").addOption(j[i].optionValue, j[i].optionDisplay, false);
			  }
			  //swap out the image
			 $('#FlavorArray').attr({ src: "../images/imgFlavorArray_"+ curProduct +".gif"});
			})
		} else {
			$("select#ProductID_1").empty();
				$("select#ProductID_1").addOption('', 'Any Flavor', false);
			$("#ProductFlavor").slideUp();
		}
	})

	// Search Tabs
	$("#advancedSearch").tabs({fxFade: true, fxSpeed: 'fast'});
	$("select#ProductID_2").selectOptions("");
	$("#ProductFlavor").hide();

	// Send to friend
	$("#icnSend").toggle(function(){ // Odd click function
		hidePanels();
		$("#icnSend").addClass("on");
		$('#sendToFriend').show();
		$('#sendFriendAlertPanel').hide();
	},function(){ // Even click function
		$('#sendToFriend').hide();
		$('#sendFriendAlertPanel').html('');
		$('#sendFriendAlertPanel').hide();
		$("#icnSend").removeClass("on");
	});

	// Shopping List
	$("#icnAdd").toggle(function(){
		hidePanels();
		$("#icnAdd").addClass("on");
		$('#shoppingList').show();
	},function(){
		$("#icnAdd").removeClass("on");
		$('#shoppingList').hide();
	});

	// My Recipes
	$("#icnAddRecipes").toggle(function(){
		hidePanels();
		$("#icnAddRecipes").addClass("on");
		$('#myRecipes').show();
		$('#loginAlertPanel').hide();
	},function(){
		$('#myRecipes').hide();
		$("#icnAddRecipes").removeClass("on");
		$('#loginAlertPanel').html('');
		$('#loginAlertPanel').hide();
	});

	// Recipe rating
	$("#icnRate").toggle(function(){
		hidePanels();
		$("#icnRate").addClass("on");
		$('#rateRecipe').show();
	},function(){
		$("#icnRate").removeClass("on");
		$('#rateRecipe').hide();
	});
	
	// Photo Upload
	$("#icnUpload").toggle(function(){
		hidePanels();
		$("#icnUpload").addClass("on");
		$('#uploadPhoto').show();
	},function(){
		$("#icnUpload").removeClass("on");
		$('#uploadPhoto').hide();
	});

	function hidePanels(){
		if ($('#sendToFriend').is(':visible'))
			$('#icnSend').trigger("click");
		if ($('#shoppingList').is(':visible'))
			$('#icnAdd').trigger("click");
		if ($('#myRecipes').is(':visible'))
			$('#icnAddRecipes').trigger("click");
		if ($('#rateRecipe').is(':visible'))
			$('#icnRate').trigger("click");
		if ($('#uploadPhoto').is(':visible'))
			$('#icnUpload').trigger("click");
	}
	
	$('#icnPrint').click(function(){
		printRecipe('recipeResults');
		this.blur();
		return false;
	});

	$('#icnSend').click(function(){
		this.blur();
		return false;
	});

	$('#icnAdd').click(function(){
		this.blur();
		return false;
	});

	$('#icnAddRecipes').click(function(){
		this.blur();
		return false;
	});

	$('#icnRate').click(function(){
		this.blur();
		return false;
	});
	
	 $('#icnUpload').click(function(){
		this.blur();
		return false;
	});
	
	$('#sendFriendAlertPanel').hide();

	
	$('a.recipeClose').click(function(){this.blur();hidePanels();return false;})
	$('a.recipeOpen').click(function(){this.blur();$('#icnUpload').trigger('click');return false;});
	
	$('#recipeRating').rating('recipe.cfm?doAction=rateRecipe', {maxvalue:5});
});

var listDone = false;
var recipeDone = false;

function addRecipe(linkID, recipeID, recipeCuisine, recipeName){
	if(!recipeDone){
		try{
			var d = new Object;
			d.doAction = 'addToMyRecipesAjax';
			d.recipeID = recipeID;
			d.recipeCuisine = recipeCuisine;
			d.recipeName = recipeName.replace(/\'/g, '\\\'');
			$.post(locationpathname, d, function(data){
				$('#linkDiv').empty();
				$('#linkDiv').attr('class', 'removeBtnFlipped');
				$('#linkDiv').html('<a href="' + location.pathname + '?doAction=removeFromMyRecipes' +
						'&RecipeID=' + recipeID +
						'&RecipeCuisine=' + recipeCuisine + 
						'&RecipeName=' + recipeName + '"' + 
						' onclick="return removeRecipe(this, ' + recipeID + ', \''+ recipeCuisine +'\', \''+ recipeName +'\');">' +
						'<strong>Remove ' + recipeName + '</strong> from My Recipes<span>remove</span></a>');
			});
			recipeDone = true;
			linkID.blur();
			return false;
		}
		catch(e){
			return true;
		}
	}else{
		linkID.blur();
		return false;
	}
}

function removeRecipe(linkID, recipeID, recipeCuisine, recipeName){
	try{
		d = new Object;
		d.doAction = 'removeFromMyRecipesAjax';
		d.recipeID = recipeID;
		$.post(location.pathname, d, function(data){
				$('#linkDiv').empty();
				$('#linkDiv').attr('class', 'addBtnFlipped');
				$('#linkDiv').html('<a href="' + location.pathname + '?doAction=addToMyRecipes' +
						'&RecipeID=' + recipeID +
						'&RecipeCuisine=' + recipeCuisine + 
						'&RecipeName=' + recipeName + '"' + 
						' onclick="return addRecipe(this, ' + recipeID + ', \''+ recipeCuisine +'\', \''+ recipeName.replace(/\'/g, '\\\'') +'\');">' +
						'<strong>Add ' + recipeName + '</strong> to My Recipes<span>add</span></a>');
		});
		recipeDone = false;
		linkID.blur();
		return false;
	}
	catch(e){
		return true;
	}
}

function addShopping(recipeID, ingredients_OnHand){
	try{
		var d = new Object;
		d.doAction = 'addToShoppingListAjax';
		d.recipeID = recipeID;
		d.ingredients_OnHand = ingredients_OnHand;
		$.post('/rar_recipes/search/recipe.cfm', d, function(data){
			// The item will always exists, because you can only add the current recipe
			var recipeName = $('#listItem'+recipeID+' a').html();
			$('#listItem'+recipeID+' div').attr('class', 'removeBtn');
			$('#listItem'+recipeID+' div').html('<a href="'+location.pathname+'?doAction=deleteFromShoppingList&RecipeID='+recipeID+'" onclick="return deleteShopping('+recipeID+', '+recipeID+');">'+recipeName+'</a>');
			$('#listItem'+recipeID+' div strong').html('Remove');
		});
		return false;
	}
	catch(e){
		return true;
	}

}

function deleteShopping(recipeID, formRecipeID){
	try{
		d = new Object;
		d.doAction = 'deleteFromShoppingListAjax';
		d.recipeID = recipeID;
		$.post(location.pathname, d, function(data){
			data = $.trim(data);
			valid = data.split('|')[0];
			msg = data.split('|')[1];
			// For the most part, we are going to want to just delete the li
			if(recipeID != formRecipeID){
				$('#listItem'+recipeID).remove();
			}
			// If they are removing the current recipe, we want to swap it out with a add option.
			else {
				var recipeName = $('#listItem'+recipeID+' a').html();
				$('#listItem'+recipeID+' div').attr('class', 'addBtn');
				$('#listItem'+recipeID+' div').html('<a href="'+location.pathname+'?doAction=addToShoppingList&RecipeID='+recipeID+'" onclick="return addShopping('+recipeID+', \'\');">'+recipeName+'</a>');
				$('#listItem'+recipeID+' div strong').html('Add');
			}
			listDone = false;
		}); 
		return false;
	}
	catch(e){
		return true;
	}
}

function sendFriend(formID){
	try{
		if($('#sendFriendAlertPanel').is('.visible')){
			$('#sendFriendAlertPanel').hide();
		}
		var msgPanel = document.getElementById('sendFriendAlertPanel');
		var valid = true;
		var msg = '';
		var d = new Object;
		msgPanel.innerHTML = '&nbsp;';
		if (isBlank(formID.Friends_Name.value)){
			valid = false;
			msg = msg + '<li class="alert_warning">\'Friends Name\' is required.</li>';
		}
		if (!isEmail(formID.Friends_Email.value)){
			valid = false;
			msg = msg + '<li class="alert_warning">\'Friends Email\' must be a valid email address.</li>';
		}
		if (isBlank(formID.Your_Name.value)){
			valid = false;
			msg = msg + '<li class="alert_warning">\'Your Name\' is required.</li>';
		}
		if (!isEmail(formID.Your_Email.value)){
			valid = false;
			msg = msg + '<li class="alert_warning">\'Your Email\' must be a valid email address.</li>';
		}
		if (isBlank(formID.Message.value)){
			valid = false;
			msg = msg + '<li class="alert_warning">Please enter a short message.</li>';
		}
		if(formID.Message.value.length>100){
			valid = false;
			msg = msg + '<li class="alert_warning">Your message may only be 100 characters or less in length.</li>';
		}
		if(valid){
			d.doAction = 'ajaxSendFriend';
			d.recipeID = formID.recipeID.value;
			d.Friends_Email = formID.Friends_Email.value;
			d.Friends_Name = formID.Friends_Name.value;
			d.Your_Name = formID.Your_Name.value;
			d.Your_Email = formID.Your_Email.value;
			d.Message = formID.Message.value;
			$.post(location.pathname, d, function(data){
				data = $.trim(data);
				valid = data.split('|')[0];
				msg = data.split('|')[1];
				switch(valid){
					case 'true':
						formID.reset();
						break;
					case 'false':
						// Nothing should happen accept for displaying error messages to the end-user
						break;
					default:
						msg = msg + 'We were unable to process your request at this time, please try again later.<br/>';
				}
				msgPanel.innerHTML = msg;
			});
		}
		msgPanel.innerHTML = '<ul>' + msg + '</ul>';
		if(!$('#sendFriendAlertPanel').is('.visible')){
			$('#sendFriendAlertPanel').show();
		}
		return false;
	}
	catch(e){
		return true;
	}
}
// A utility function that returns true if a string contains only 
// whitespace characters.
function isBlank(str) {
	if ((str == null) || (str == ""))
		return true;

	for(var i = 0; i < str.length; i++) {
			var c = str.charAt(i);
			if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

// A utility function that returns true if a string is a valid email.
function isEmail(str) {
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported){
		if ((str.indexOf(".") == 0) || (str.indexOf("@") == 0)){
			return false;
		} else {
			return true;
		}
	}
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  if (!r1.test(str) && r2.test(str)){
		return true;
	} else {
		return false;
	}
}
