$(document).ready(function(){
	
	// Make sure the keyword field isn't empty when the page loads.
	if($("#search-field").val() == ""){
		$("#search-field").val("Enter some keywords")
	}
	
	// Make sure the default keyword field value doesn't get submitted
	$("#searchForm").submit(function(){
		if($("#search-field").val() == "Enter some keywords"){
			$("#search-field").val("");
		} 
		return true
	});
	
	//Show a boxy window with the loading indicator when ajax requests fire
	$().ajaxStart(function(){
		var loading = new Boxy("<div id='loading'><h3>Loading</h3></div>",{
			closeable:false,
			draggable:false,
			center:true,
			modal:true,
			unloadOnHide:true
		});
		// We want the modality, but not the blackout, so we make the blackout div see-thru
		$(".boxy-modal-blackout").css("opacity","0")
	});


	// Hide the loading indicator
	$().ajaxStop(function(){
			Boxy.get("#loading").hide();
			// Put the blackout div opacity back to normal just to be safe.
			$(".boxy-modal-blackout").css("opacity","0.1")
	});	

	var kwDef = "Enter some keywords";
	var locDef = $("#loc").val();
	$("#search-field,#loc").focus(function(){
		$(this).select().removeClass("dim");
	}).blur(function(){
		if($(this).val() == ""){
			if($(this)[0].id == "search-field"){
				if($(this).val() == kwDef){
					$(this).addClass("dim");
				}
			}else{
				if($(this).val() == locDef){
					$(this).addClass("dim");
				}
			}
		}
	});
	
	// Add an active class to the last-clicked filter
	$("#filters li").click(function(){
		$("#filters li").each(function(){
			$(this).removeClass("active");
		});
		$(this).addClass("active");
	});
});

//Add a challenge to a users myChallengeCollection
function addChallenge(e,challengeId){

	var currentSort = $("#currentsort").val();
	var currentDir = $("#currentdir").val();
	
	$.post("app/myChallengeServlet:addChallenge",{id:challengeId, redirect:"/findchallenge:challengeSearch?sort=" + currentSort + "&dir=" + currentDir},
	    function( data, textStatus ){
			//var mynewdiv2 = $("#list-1", data ).html();
			//$("#list-1").html( mynewdiv2 );
			$("#badgediv_" + challengeId).html($("#badgediv_" + challengeId,data).html());
			$("#messages").html( $("#messages",data).html());
	    }, "html");
};

// Remove a challenge from a users myChallengeCollection
function removeChallenge( e,challengeId ) {

	var currentSort = $("#currentsort").val();
	var currentDir = $("#currentdir").val();
	
    $.post("app/myChallengeServlet:removeChallenge",{id:challengeId, redirect:"/findchallenge:challengeSearch?sort=" + currentSort + "&dir=" + currentDir},
        function( data, textStatus ){ 
			//var mynewdiv2 = $("#list-1", data ).html();
			//$("#list-1").html( mynewdiv2 );
			$("#badgediv_" + challengeId).html($("#badgediv_" + challengeId,data).html());
			$("#messages").html( $("#messages",data).html());
        }, "html" );
};
