$(document).ready(function(){


		/*Start invite and win promo javascript*/
		$("#iawTop").click(function(){
			//Do the slide down here
			$("#iawBottom").show();
			$("#iawBottom").animate({height: "245px"}, function(){
			$("#rulesAndRegs").fadeIn("slow");
			});
		});

		$("#iawBottom").click(function(){
			$("#winnersList").fadeOut("fast");
			//Do the slide up here
			$("#rulesAndRegs").fadeOut("fast", function(){
				$("#iawBottom").animate({height: "1px"});
			});
		});
		
		$("#showWinners").click(function(){
			//Do the fade in here
			$("#winnersList").fadeIn("slow");
		});
		
		$("#hideWinners").click(function(){
			//Do the fade out here
			$("#winnersList").fadeOut("slow");
		});
		
		/*End invite and win promo javascript*/
		
		
		
		//Get and show the recipe details
		$(".recipe_details_btn_small").live("click", function(){ 
			var theId = $(this).attr("rel");
			$.ajax({url: "/myEvent/rpc.php?action=singleRecipe&id="+theId, 
				success: function(data){
					//For some bizzare reason, jQuery just wont work in IE using .append, .html ... resorted to simple JS
					document.getElementById('recipeDetailHolder').innerHTML = data;
					$("#recipeDetailHolder").fadeIn();
				}
			});
		});
		
		//Details for items on the shopping list
		$(".savedRecipes").live("click", function(){ 
			var theId = $(this).attr("alt");
			$.ajax({url: "/myEvent/rpc.php?action=singleRecipe&id="+theId, 
				success: function(data){
					//For some bizzare reason, jQuery just wont work in IE using .append, .html ... resorted to simple JS
					document.getElementById('recipeDetailHolder').innerHTML = data;
					$("#recipeDetailHolder").fadeIn();
					
				}
			});
		});
		
		//Go through the checklist, remove any "add recipe" buttons that are already on the list
		$(".savedRecipes").each(function(i){
			var checklistRecipeId = $(this).attr("rel");
			$(".addThisToChecklist").each(function(ii){
				var loadedRecipesIds = $(this).attr("rel");
				if (checklistRecipeId == loadedRecipesIds){
					$(this).hide();
				}
			});
		});
		
		//Remove items from the list
		$(".deleteItem").live("click", function(){
			//custom item or recipe?
			var delId = $(this).attr("alt");
			var parentElm = $(this);
			var classItemToDel = ".deleteItem"+delId;
			var shoppingListId = $(classItemToDel).attr("rel");
			var fbid = $("#userFbid").val();
			$.ajax({	url: '/myEvent/rpc.php?action=deletechecklistitem&fbid='+fbid+'&cid='+shoppingListId,
					type: "POST",
					success: function(data){
						//Remove item from list
						if (data == "good"){
							$(classItemToDel).fadeOut();
							$(classItemToDel).remove();
							$(parentElm).fadeOut();
							$(parentElm).remove();
							$("#hrId"+delId).remove();
						}else{
							$("#checklistResponse").fadeOut().html("Server side error. Please try again in a minute.").fadeIn();
						}
					}
			});
		});
		
		//Removes unsaved items from the list
		$(".unsavedItem").live("click", function(){
			var theId = "#"+$(this).attr("id").replace('check_', '');
			$(theId).next("hr").fadeOut();
			$(theId).fadeOut();
		});
		
		//Add the recipe to the checklist
		$(".addThisToChecklist").live("click", function(){
			var recipeId = $(this).attr("rel");
			if (isNumeric(recipeId)){
				//Make sure it's not already on the list
				var onList = false;
				$(".savedRecipes").each(function(i){
					var savedId = $(this).attr("alt");
					if (savedId == recipeId){
						onList = true;
						return false; //return false; breaks out of the .each loop
					}
				});
				if (!onList){
					$("#noneAdded").html("");
					//It's a full recipe
					var theTitle = $("#title"+recipeId).html();
					var insertThis = "<a alt=\""+recipeId+"\" class=\"savedRecipes\" id=\"recipeLink"+recipeId+"\">"+theTitle+"</a><input type=\"hidden\" name=\"recipeItem[]\" value=\""+recipeId+"\" />";
					$("#checklistItems").append(newChecklistItem(insertThis));
					var parentThis = this;
					$(this).effect("transfer", { to: "#recipeLink"+recipeId }, 500, function(){
						$(parentThis).fadeOut(); //Can't add it again!
					});
					isDirty = true;
				}
			}
		});
		
		//Add items from the custom text box
		$("#add_items_btn").live("click", function(){
			//Add from text box
			$("#noneAdded").html("");
			var theTitle = $("#customItem").val();
			if (theTitle != ""){
				var insertThis = theTitle+" <input type=\"hidden\" name=\"customItem[]\" value=\""+theTitle+"\" />";
				$("#checklistItems").append(newChecklistItem(insertThis));
				$("#customItem").val("");
				isDirty = true;
			}
		});
		
		
		var suggestions = new Array(	"Birthday party? Balloons, candles, moon bounce, party hats...", 
						"Dinner party? Wine glasses, dinner candles, napkin holders, salad tongs...",
						"Baby shower? Baby books, games, tiny party hats...",
						"Bachelor(ette)? Limo, shot glasses, guest list for that club, camera...");
		var randIndex = randRange(0,3);
		var suggestThis = suggestions[randIndex];
		$("#customItem").val(suggestThis);
		/*$("#customItem").blur(function(){
			if ($(this).val() == ""){
				$("#customItem").css({color: "#919191"});
				var randIndex = randRange(0,3);
				var suggestThis = suggestions[randIndex];
				$("#customItem").val(suggestThis);
			}
		});*/
		//Add suggestions for the text area
		$("#customItem").click(function(){
			var exampleCheck = false;
			for (var i = 0; suggestions.length > i; i++){
				if ($(this).val() == suggestions[i]){
					exampleCheck = true;
				}
			}
			if (exampleCheck){
				$("#customItem").css({color: "#000000"});
				$(this).val("");
			}
		});
		
		//Close the recipe detail
		$(".back_to_recipes").live("click", function(){
			$("#recipeDetailHolder").fadeOut();
		});

		$(".pagination").live("click", function(){
			var theRel = $(this).attr("rel");
			var theCat = $("#currentCategory").html();
			$(".pagination").css({fontWeight: "normal", color: "#919191"});
			$(this).css({fontWeight: "bolder", color: "#900"});
			$("#recipesMainHolder").load("/myEvent/rpc.php?action=moreRecipes&category="+theCat+"&gofrom="+theRel, {}, function(){
				//Go through the checklist, remove any "add recipe" buttons that are already on the list
				$(".savedRecipes").each(function(i){
					var checklistRecipeId = $(this).attr("rel");
					$(".addThisToChecklist").each(function(ii){
						var loadedRecipesIds = $(this).attr("rel");
						if (checklistRecipeId == loadedRecipesIds){
							$(this).hide();
						}
					});
				});
			});
		});
		
		$("#recipeCategories").change(function(){
			var theRel = $(this).val();
			$("#currentCategory").html(theRel);
			$("#recipesMainHolder").load("/myEvent/rpc.php?action=moreRecipes&gofrom=0&category="+theRel, {}, function(){
				//Go through the checklist, remove any "add recipe" buttons that are already on the list
				$(".savedRecipes").each(function(i){
					var checklistRecipeId = $(this).attr("rel");
					$(".addThisToChecklist").each(function(ii){
						var loadedRecipesIds = $(this).attr("rel");
						if (checklistRecipeId == loadedRecipesIds){
							$(this).hide();
						}
					});
				});
			});
			//Update pagination
			$("#pagesHolder").load("/myEvent/rpc.php?action=moreRecipesPages&category="+theRel);
		});

		$("#save_list_btn").live("click", function(){
			var total = 0;
			$("#checklistForm input[type='hidden']").each(function(i){
				total++;
			});
			if (total > 2){ //There are always two hidden fields
				var eventId = $('[name="eventid"]').val();
				$.ajax({	url: '/myEvent/rpc.php?action=savechecklist',
						data: $("#checklistForm").serialize(),
						type: "POST",
						success: function(data){
							//alert("Checklist has been saved");
							$("#checklistResponse").fadeOut().html("You Have Saved List!<br/><a href='/myEvent/myEvents.php?action=guestlist&id="+eventId+"'><img src='images/checklist_step5.jpg' border='0'/></a>").fadeIn();
							isDirty = false;
						}
				});
			}
		});
		
		$("#clear_list_btn").live("click", function(){
			var total = 0;
			$("#checklistForm input[type='hidden']").each(function(i){
				total++;
			});
			if (total > 2){ //There are always two hidden fields
				if (confirm("Are you sure you want to clear your checklist?")){
					$("#checklistItems").html("");
						$.ajax({	url: '/myEvent/rpc.php?action=clearchecklist',
								data: $("#checklistForm").serialize(),
								type: "POST",
								success: function(data){
									//alert("Checklist has been cleared");
									$("#checklistResponse").fadeOut().html("Checklist has been cleared.").fadeIn();
									isDirty = false;
								}
						});
				}
			}
		});
	});
	
function initFB(){
	FB_RequireFeatures(["XFBML"], function(){
		FB.init("4400af914543791afde87338a99fc1ce", "xd_receiver.htm");
	});
}

function movetoLanding(){
	window.location = "http://blackdiamond.bluebandmedia.com/myEvent/myEvents.php";
	// because this is XFBML, we need to tell Facebook to re-process the document
	//FB.XFBML.Host.parseDomTree(); 

}

function movetoRSVP(eventId){
	window.location = "http://blackdiamond.bluebandmedia.com/myEvent/rsvp.php?id="+eventId;
	// because this is XFBML, we need to tell Facebook to re-process the document
	//FB.XFBML.Host.parseDomTree(); 
}

function newChecklistItem(lineItem){
	var theId = lineItem.replace(/[^a-zA-Z0-9]+/g,'');
	var theHTML = "<table id=\""+theId+"\" class=\"lineItem\"><tr><td><img src=\"images/checkbox.jpg\" id=\"check_"+theId+"\" class=\"unsavedItem\" alt=\" \" width=\"35\" height=\"31\"/></td><td style=\"width:150px;\">"+lineItem+"</td></tr></table><hr size=1 color=\"#888888\" style=\"margin:7px;\">";
	return theHTML;
}


//Misc utility functions from here on
function is_valid_email (email)
{
	return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}

function isValidPostalcode(postalcode) {
	if (postalcode.length == 6 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/) != -1) return true;
	else if (postalcode.length == 7 && postalcode.search(/^[a-zA-Z]\d[a-zA-Z](-|\s)\d[a-zA-Z]\d$/) != -1) return true;
	else return false;
}


function isNumeric(sText){
	//Will implement a RegEx version later
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for (var i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
			IsNumber = false;
	}
	return IsNumber;   
}

function randRange(min, max){
  return Math.round(Math.random() * (max - min) + min);
}

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function playInviteAndWin(eventId){
	//Add "Black Diamond" to this events guest list
	$.ajax({	url: '/myEvent/rpc.php?action=inviteAndWinEntry&eventId='+eventId,
			success: function(data){
				//alert("Checklist has been cleared");
				if (data == "good"){
					$("#inviteAndWin").attr("src", "/myEvent/images/invite_and_win_invitepage_complete.jpg");
					$("#inviteAndWin").parent().attr("href", "javascript: void(0);");
				}
			}
	});
}


