
function isdefined(variable) {
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function showLoginForm() {
	Boxy.load('/signUp/logIn.null', {
		modal: true,
		afterShow: function() {
			var username = $.cookie("username");
			if (username) {
				$("#j_username").val(username);
				$("#passwordPlain").focus();
			} else {
				$("#j_username").focus();				
			}
			FB.ensureInit(renderXFBML);
		}
	});
}

function showJoinNowForm() {
	Boxy.load('/signUp/joinNow.null', {
		modal: true,
		afterShow: function() {
			createReCaptcha();
			FB.ensureInit(renderXFBML);
			
			pageTracker._trackPageview("/signUp/joinNow.null");
		} 
	});
}

function createReCaptcha() {
	if (isdefined("Recaptcha")) {
		Recaptcha.create("6LczYgcAAAAAAIYc5MJ3_MueSQvIedTrnwfVZGrV",
			"captcha_div", {
			   theme: "clean",
			   callback: Recaptcha.focus_response_field
		});
	} else {
		window.setTimeout(createReCaptcha, 200);			
	}
}

function showInviteFriendDialog() {
	if (!currentUserCheck()) {
		return false;
	}
	Boxy.load('/users/showInviteDialog.null', {
		modal: true,
		afterShow: function() {
			$('#invite_receivers').focus();			
		}
	});
}

function showSendMessageDialog(userId) {
	if (!currentUserCheck()) {
		return false;
	}
	Boxy.load('/users/showSendMessageDialog.null?userId='+userId, {
		modal: true,
		afterShow: function() {
			$('#message').focus();		
		}
	});
}

function showBuyCoinPackDialog() {
	if (!currentUserCheck()) {
		return false;
	}
	Boxy.load('/payment/buyCoinPack.null', {
		modal: true,
		afterShow: function() {
			
		}
	});
}

function fixIE6flicker(fix) {
	try {
		document.execCommand("BackgroundImageCache", false, fix);
	} catch(err) { }
}


$(document).ready(function(){
	fixIE6flicker(true);
	showMainMenu();
	//hoverAutoTabs();
	toggleBoxes();
	showQuickhelps();
	makeTabs();
	makeTabsForLevelBrowser();
	makeSmallTabs();
	makeSlidingBoxes();
	editProfileDialog();
	makeEasyTabs();
	makeSelects();
	
	
	$("#logo").bind("ajaxComplete", function(event, XMLHttpRequest, ajaxOptions){
		var trackUrl = ajaxOptions.url.replace(/^http\:\/\/(www\.)*/i, "");
		var splitUrl = trackUrl.split("/");
		var category = splitUrl[1];
		var action = "";
		if (splitUrl.length > 3) {
			action += splitUrl[2]+" - ";	
		}
		var lastUrlParameter = splitUrl[splitUrl.length-1];
		var lastUrLParameterList = lastUrlParameter.split("?");
		action += lastUrLParameterList[0];
		var actionValue = "";
		if (lastUrLParameterList.length > 1) {
			actionValue = lastUrLParameterList[1];
		}
		
		if (pageTracker) {
			pageTracker._trackEvent(category, action, actionValue);
		}
   		if (window.renderFacebookXFBML) {
			FB.ensureInit(renderXFBML);
		}
 	});
	
	$("#user_find").focus(function() {
        if ($(this).val() == "Find new friends") {
			$(this).val('');
		}
    });

});

// ----------------------------------------------------------------------------
// MAIN MENU

function showMainMenu() {
	$("#menu > li").hover(
	  function () {
		$(this).addClass("hover");
	  }, 
	  function () {
		$(this).removeClass("hover");
	  }
	);
	
	$("#menu_loggedin > li").hover(
	  function () {
		$(this).addClass("hover");
	  }, 
	  function () {
		$(this).removeClass("hover");
	  }
	);
}


// ----------------------------------------------------------------------------
// HOVER STATES AUTO_SIZE TABS

function hoverAutoTabs() {
	$(".tabs ul > li.auto_size").hover(
	  function () {
		$(this).addClass("hover");
	  }, 
	  function () {
		$(this).removeClass("hover");
	  }
	);
	$(".small_tabs > li").hover(
	  function () {
		$(this).addClass("hover");
	  }, 
	  function () {
		$(this).removeClass("hover");
	  }
	);
}


// ----------------------------------------------------------------------------
// USER PROFILE

function editProfileDialog() {
	$(".edit_profile").click(function() {
		Boxy.load("/users/editProfile.null", {
			modal: true,
			afterShow : function() {
				makeEasyTabs();
				makeSelects();
				FB.ensureInit(renderXFBML);
			}
		});
		return false;
	});
}

function removeAccountWithReason(isFacebookUser) {
	var answer = confirm("Do you really want to leave Platogo?")
	if (answer){
		$(".boxy-content form.removeAccountForm").ajaxSubmit({
			url: "/users/disableUser.null",
			type: "post",
			dataType: "xml",
			success: function(x) {
				if ($(x).find('status').text() == 'OK') {
					logout(isFacebookUser);
				} else {
					alert($(x).find('error-msg').text());				
				}
			}
		});
	}
	else{
		alert("Thanks for sticking around!")
	}

}

// ----------------------------------------------------------------------------
// DEVELOPER PROFILE

function editDeveloperProfileDialog(developerId) {
	Boxy.load("/developers/editDeveloper.null?developerId=" + developerId, {
		modal: true,
		afterShow : function() {
			makeEasyTabs();
			makeSelects();
			
			$("#edit_dev_find").autocomplete("/users/search.null", {
		  		max: 10,
		  		formatItem: function(item) {
		    		return "<img class='pic_small' src='"+STATIC_CONTENT_URL+"/users/" + item[1] + "/avatar.jpg' /> " + item[0];
			  	}
			});
			
			$("#edit_dev_find").result(function(event, data, formatted) {
				$("#add_member_button").removeClass('inactive');
			});
				
		}
	});
	return false;
}


// ----------------------------------------------------------------------------
// EASY TABS
// Creates Tabs for content that has been loaded (Hides content of unselected tabs).
// You need: 
// UL class: easyTabs
// UL > LI > A: active or not
// .easyTabBox > DIV.easyTab as tab-content
function makeEasyTabs() {
	/*$("ul.easyTabs a").removeClass("active");
	$("ul.easyTabs").find("a:first").addClass("active");
	$("ul.easyTabs li").removeClass("active");
	$("ul.easyTabs").find("li:first").addClass("active");
	
	$("ul.easyTabs").parents(".easyTabBox").find(".easyTab").hide();
	$("ul.easyTabs").parents(".easyTabBox").find(".easyTab:first").show();*/
	
	$("ul.easyTabs a").click(function() {
		$(this).parents("ul.easyTabs:first").find("a").removeClass("active");
		$(this).parents("ul.easyTabs:first").find("li").removeClass("active");
		$(this).addClass("active");
		$(this).parent().addClass("active");
		
		// ie7 hack
		var tabIdHref = $(this).attr("href");
		var tabId = tabIdHref.substring(tabIdHref.indexOf("#"));
		
		$(this).parents(".easyTabBox:first").find(".easyTab").hide();
		$(tabId).show();
		return false;
	});	
}

// ----------------------------------------------------------------------------
// DIALOGS

function closeDialog(obj) {
	var b = $("div.boxy-wrapper:first").data("changes");
	var changesSaved = $("div.boxy-wrapper:first").data("changesSaved");
	if (b) {
		$("div.boxy-wrapper:first").find("div.footer").hide();
		$("div.boxy-wrapper:first").find("div.footer.warning").show();
	} else if(changesSaved) {
		window.location.reload();
	}
	else {
		Boxy.get(obj).hideAndUnload();		
	}
	return false;
}

function resetChanges() {
	$("div.boxy-wrapper:first").data("changes", false);
}

function blockSavingOfDialog() {
	resetChanges();
	var b = $("div.boxy-wrapper:first");
	b.data("changes", true);
	$(".dialog_save_button", b).addClass("inactive");
}

function closeWithoutSavingChanges(obj) {
	resetChanges();
	closeDialog(obj);
	return false;
}

function dialogChanged(obj) {
	var b = $("div.boxy-wrapper:first");
	b.data("changes", true);
	$(".dialog_save_button", b).removeClass("inactive");
	
	$("div.boxy-wrapper:first").find("div.footer").show();
	$("div.boxy-wrapper:first").find("div.warning").hide();
}

function showAddFriendDialog(userId, pageType) {
	Boxy.load('/users/showAddFriendDialog.null?userId=' + userId +'&pageType=' + pageType,
	{	modal: true,
		afterShow: function() {
				createReCaptcha();
		}
	});
}

function requestFriendship(obj, username, pageType, userId) {
	$(".boxy-content form.requestFriendShipForm").ajaxSubmit({
		url: "/user/requestFriendship.null",
		type: "post",
		success: function(xml) {
		    var response = $(xml).find('status').text();
		    if (response == "OK") {
				Boxy.get(obj).hideAndUnload();
				if (pageType == "profile") {
					$("#request_friendship_action").html("<p><span class='username'>" + username + "</span> needs to confirm your friend request!</p>");
				}
				else if (pageType == "searchResult") {
					/* in showSeachResults.ftl dupliziert */
					$('a[rel="' + userId + '"]').parent().html('<span class="button inactive"><span><span><span>Request sent</span></span></span></span>');
				}
			} else {
				createReCaptcha();
			}
		}
	});	
}

// ----------------------------------------------------------------------------
// TEXTAREAS

function checkMax(obj, max, target) {
	var current = $(obj).val().length;
	$("#"+target).html("" + (max - current));
	
	if (current >= max) {
		$(obj).val($(obj).val().substring(0,max-1));
	}
}


// ----------------------------------------------------------------------------
// SELECTS

function makeSelects() {
	$("div.p_select").each(function() {
		var select = this;
		// var activeOption = $("span.activeOption", select).html();
		var activeValue = $("input", select).val();
		$("div.p_select_popup a[rel='"+activeValue+"']", select).addClass("active");
		
		$("div.p_select_field a", select).click(function() {
			if($("div.p_select_popup", select).css('display') == 'none'){
				$("div.p_select_popup").hide();
			}
			$("div.p_select_popup", select).toggle(); 
			return false;
		});
		
		$("div.p_select_popup a", select).click(function() {
			$("div.p_select_popup a.active", select).removeClass("active");
			$(this).addClass("active");
			
			var option = $(this).html();
			var value = $(this).attr('rel');
			$("span.activeOption", select).html(option);
			$("input", select).val(value);
			
			$("div.p_select_popup", select).hide(); 
			return false;
		});
	});
}

// ----------------------------------------------------------------------------
// GAME FAVORITE

function addGameFavorite(theGameId) {
	if (!currentUserCheck()) return false;
	$.get('/games/'+GAME_LINK+'/addGameFavorite.null', { gameId: theGameId }, function(xml) {
    	var response = $(xml).find('status').text();
    	if (response == "OK") {
    		var timesFavored = $(xml).find('times-favored').text();
    		$("#times-favored-game").html(timesFavored);
			$("#link-fan-"+theGameId).html("<span class='link_fan_active'>You're a fan</span> <a href='#RemoveGameFavorite' onclick='removeGameFavorite("+theGameId+");return false;'>(Quit)</a></li>");
			changeAndLoadBox("#game-fans-box ul a:first", "page", 1);
    	}
	}, 'xml');
}

function removeGameFavorite(theGameId) {
	if (!currentUserCheck()) return false;
	$.get('/games/'+GAME_LINK+'/removeGameFavorite.null', { gameId: theGameId }, function(xml) {
    	var response = $(xml).find('status').text();
    	if (response == "OK") {
    		var timesFavored = $(xml).find('times-favored').text();
    		$("#times-favored-game").html(timesFavored);
    		$("#link-fan-"+theGameId).html("<a href='#AddGameFavorite' class='link_fan' onclick='addGameFavorite("+theGameId+");return false;'>Become a fan</a>");
			changeAndLoadBox("#game-fans-box ul a:first", "page", 1);
    	}
	}, 'xml');
}

// ----------------------------------------------------------------------------
// DEVELOPER FAVORITE

function addDeveloperFavorite(theDeveloperId) {
	if (!currentUserCheck()) return false;
	$.get('/developers/addDeveloperFavorite.null', { developerId: theDeveloperId }, function(xml) {
    	var response = $(xml).find('status').text();
    	if (response == "OK") {
    		var timesFavored = $(xml).find('times-favored').text();
			$("#total-developer-fans").html(timesFavored);
			
			changeAndLoadBox($("#times-favored-developer-link"), "page", 1);
    	}
	}, 'xml');
}

function removeDeveloperFavorite(theDeveloperId) {
	if (!currentUserCheck()) return false;
	$.get('/developers/removeDeveloperFavorite.null', { developerId: theDeveloperId }, function(xml) {
    	var response = $(xml).find('status').text();
    	if (response == "OK") {
    		var timesFavored = $(xml).find('times-favored').text();
			$("#total-developer-fans").html(timesFavored);
			
			changeAndLoadBox($("#times-favored-developer-link"), "page", 1);
    	}
	}, 'xml');
}

// ----------------------------------------------------------------------------
// TAGS

function showAddLevelTagForm(id) {
	if (!currentUserCheck()) return false;
	$(".add_tags_form").hide();
	$("#add_tags_form_"+id).show();
	$("#add_tags_form_"+id+" input").focus();
}

function checkAddTag(event, levelId) {
	var value = "" + $("#add_tags_"+levelId).val();
	if (value.length >= 2) {
		$("#add_tags_button_"+levelId).removeClass("inactive");
	} else {
		$("#add_tags_button_"+levelId).addClass("inactive");		
	}

	var code = (event.which == null) ? event.keyCode : event.which;
	if (code == 13) {
		$("#add_tags_button_"+levelId).trigger('click');
	}
}

function addLevelTag(id) {
	if ($("#add_tags_button_"+id).hasClass("inactive")){
		return false;
	}
	
	var tag = $("#add_tags_" + id).val();
	
	$.get('/games/'+GAME_LINK+'/addLevelTag.null', {levelId: id, tagName: tag}, function(xml) {
		if ($(xml).find("status").text() == 'OK') {
			if (jQuery.trim($("#level_tags_"+id).text())!="") {
				$("#level_tags_"+id).append(", ");
			}
			var tagId = $(xml).find("tag-id").text();
			//$("#level_tags_"+id).append("<a href='#' onclick='limitTag(this); return false;'>"+tag.toLowerCase()+"</a>");
			if ($("#tags_level_" + id + " p.empty_state").length > 0) {
				$("#tags_level_" + id + " p.empty_state").remove();
				$("#tags_level_" + id).prepend("<h4 class='inline_header'>Tags: </h4><p class='link_list' id='level_tags_" + id + "'/>");
			}
			$("#level_tags_"+id).append("<a href='#' onclick='limitTag(this); return false;'>"+tag.toLowerCase()+"</a>");
			$("#add_tags_" + id).val("");
		} else {
			var errorText = $(xml).find("error-msg").text();
			var errorField = $("#add_tags_form_"+id+" p.error_text");
			errorField.html(errorText).show("slow");
			window.setTimeout(function() {
				errorField.hide("slow");
			}, 3000);
		}
	}, 'xml');
	
	return false;
}

function removeLevelTag(obj, levelId, tagName) {
	if (window.confirm("Really remove " + tagName + "?")) {
		$.get('/games/'+GAME_LINK+'/removeLevelTag.null', {levelId: levelId, tagName: tagName}, function(xml) {
			if ($(xml).find("status").text() == 'OK') {
				$(obj).prev().remove();
				$(obj).remove();
			}
		}, 'xml');
	}
}

function limitTag(obj) {
	var tagName = $(obj).text();
	var curFiltersWithTag = $('#selected_level_tags').find("input[value='"+tagName+"']");
	if (curFiltersWithTag.length == 0) {
		
		$("#level_categories").find("li a[rel="+tagName+"]").addClass("active");
		$("#tag_cloud").find("li a[rel="+tagName+"]").addClass("active");
		
		var tagHtml = " <li class='tag_tag'> <span><span><span>"+tagName+"</span></span></span> <a href='#' rel='"+tagName+"' onclick='removeTagFilter(this,\""+tagName+"\"); return false;'>remove</a> </li> ";
		$("#active_level_filters").show().append(tagHtml);
		$('#selected_level_tags').append("<input type='hidden' name='tags' value='"+tagName+"'>");
		
		var box = $(obj).parents("div.box:first");
		box.find("input[name='page']").val("1");
		
		$("#levels_list_view").trigger("click");
	} else {
		$("#active_level_filters li.tag_tag a[rel='"+tagName+"']").trigger("click");
	}
	checkActiveFilters();
	$(obj).blur();
}

function removeTagFilter(obj, tagName) {
	$('#selected_level_tags').find("input[value='"+tagName+"']").remove();
	var box = $(obj).parents("div.box:first");
		
	$(obj).parent().remove();
	$("#level_categories li span").each(function() {
		if ($(this).text() == tagName) {
			$(this).replaceWith("<a href='#' onclick='limitTag(this); return false;'>"+tagName+"</a>");
		}
	});
	if ($('#game_filters ul > li').length == 0) {
		$('#game_filters').hide();
	}
	$("#level_categories").find("li a[rel="+tagName+"]").removeClass("active");
	$("#tag_cloud").find("li a[rel="+tagName+"]").removeClass("active");
	
	if (getNumberOfActiveFilters() > 0) {
		$("#levels_list_view").trigger("click");
	}
	
	checkActiveFilters();
}

// ----------------------------------------------------------------------------
// FILTERS

function addFilter(filterName) {
	var currFilters = $('#selected_level_filters').find("input[value='"+filterName+"']");
	if (currFilters.length == 0) {
		$('#selected_level_filters').append("<input type='hidden' name='levelFilters' value='"+filterName+"'>");
	}
}

function removeFilter(filterName) {
	$('#selected_level_filters').find("input[value='"+filterName+"']").remove();
}

function applyLevelFilter(filterName, obj) {
	// clear all filters
	$('#selected_level_filters').empty();
	
	addFilter(filterName);
	
	var box = $(obj).parents("div.box:first");
	box.find("input[name='page']").val("1");
	loadBoxContent(box);
	$(obj).blur();
}

// ----------------------------------------------------------------------------
// SIGN IN / SIGN UP

function signIn(username, password) {
	var sha1password = SHA1(password);
	var loginData = "j_username=" + username + "&j_password=" + sha1password;

	$.post('/j_spring_security_check', {j_username: username, j_password: sha1password}, function(code) {
	    if (code == "OK") {
	    	document.location.reload();
	    } else {
	    	alert("Sorry, we could not log you in. Please check your username and password!");
	    }
	});
}


// ----------------------------------------------------------------------------
// GAME

function sharedGame(id, shareChannel) {
	if(!currentUserCheck()) return false;
	
	 $.ajax({
		   type: "GET",
		   url: "/games/" + GAME_LINK + "/shareGameInChannel.null",
		   data: "gameId=" + id + "&channel=" + shareChannel,
		   success: function(msg){
		   }
		 });
}

function rateGame(gameId, status, obj) {
	if (!currentUserCheck()) return false;
		
	if (status != "ONLINE") {
		alert('You can rate this game once it is published');
		return;
	}
	
	$('#loading-game-rating').show();
	$.get("/games/"+GAME_LINK+"/rateGame.null", {id:gameId, rating:obj.title}, function(xml) {
		var totalRated = $(xml).find('total-rated').text();
		var averageRating = $(xml).find('average-rating').text();
		$("#total-game-ratings").html(totalRated);
		$("#your-rating").html(", you: " + obj.title);
		$("#game-current-rating").css({ width: (17 * averageRating)+"px" });
		$("#game-current-rating-text").html(averageRating);
		$('#loading-game-rating').hide();
	}, 'xml');
}

function showUpcomingFeature() {
	Boxy.load("/games/"+GAME_LINK+"/showUpcomingFeature.null", {modal: true});
}

function showNoSolutionForNotLoggedInUsers() {
	Boxy.load("/games/"+GAME_LINK+"/showNoSolutionForNotLoggedInUsers.null", {modal: true});
}

function loadLevelDetails(obj, gameId, levelId, levelIndex, playLevel,swfWidth, swfHeight, swfVersion) {
	
	if(playLevel){
		 playGame(gameId,levelId, swfWidth, swfHeight, swfVersion);
	}
	
	var box = $(obj).parents("div.box:first");
	box.find("input[name='viewType']").val("SINGLE");
	box.find("input[name='levelIndex']").val(levelIndex);
	
	// change viewstate of viewtype icons
	var ul = box.find("ul.views_switch_3");
	ul.find("a").removeClass("active");
	ul.find("li").removeClass("active");
	var singleView = ul.find("a.single_view");
	singleView.addClass("active");
	singleView.parent().addClass("active");
	
	var val = $(obj).attr('rel');
	var box = $(obj).parents("div.box:first");
	box.find("input[name='levelId']").val(levelId);
	box.find("input[name='page']").val("1");
	box.find("form:first").ajaxSubmit({
		success: function(responseText, statusText) {
			 $(box).find(".target:first").html(responseText);
			 makeSmallTabs();
		}
	});
	
	$("#tooltip").remove();
	
	return false;
}

//--------------------------------------------------------------------------------------------
// BOXES

function updatePager(box, page, totalPages) {
	$(box).find("a.left").unbind();
	$(box).find("a.right").unbind();
	
	var prev = page - 1;
	var next = page + 1;

	if (totalPages <= 1) {
		$(box).find(".previous_next").hide();
		return;
	} else {
		$(box).find(".previous_next").show();
	}
	
	var pagingElems = $(box).find(".previous_next li");
	$(pagingElems[0]).find("a.left").click(function() {
		if (prev > 0) {
			changeAndLoadBox(this, "page", prev);				
		}
		$(this).blur();
		return false;
	});
	
	$(pagingElems[1]).addClass("numbers");
	$(pagingElems[1]).html("<span class='hide'>page </span>" + page + "/" + totalPages);
	
	$(pagingElems[2]).find("a.right").click(function() {
		if (next <= totalPages) {
			changeAndLoadBox(this, "page", next);				
		}
		$(this).blur();
		return false;
	});
}

function updateSmallPager(box, page, totalPages) {
	$(box).find("a.left").unbind();
	$(box).find("a.right").unbind();
	
	var prev = page - 1;
	var next = page + 1;

	if (totalPages <= 1) {
		$(box).find(".previous_next").hide();
		return;
	} else {
		$(box).find(".previous_next").show();
	}
	
	var pagingElems = $(box).find(".previous_next li");
	$(pagingElems[0]).find("a.left").click(function() {
		if (prev > 0) {
			changeAndLoadSmallBox(this, "page", prev);				
		}
		$(this).blur();
		return false;
	});
	
	$(pagingElems[1]).addClass("numbers");
	$(pagingElems[1]).html("<span class='hide'>page </span>" + page + "/" + totalPages);
	
	$(pagingElems[2]).find("a.right").click(function() {
		if (next <= totalPages) {
			changeAndLoadSmallBox(this, "page", next);				
		}
		$(this).blur();
		return false;
	});
}

function makeTabs() {
	$("div.tabs > ul:not(.level_browser_tabs) > li > a").click(function() {
		$(this).parents("ul:first").find("a").removeClass("active");
		$(this).parents("ul:first").find("li").removeClass("active");
		
		$(this).addClass("active");
		$(this).parents("li.auto_size:first").addClass("active");
		
		var key = $(this).attr("rel").split("|")[0];
		var val = $(this).attr("rel").split("|")[1];
		
		changeAndLoadBox(this, key, val, function() {
			makeSelects();
		});
		
		$(this).blur();
		return false;
	});
}

function makeSmallTabs() {
	$("div.small_header_content > ul.small_tabs > li > a").click(function() {
		$(this).parents("ul:first").find("a").removeClass("active");
		$(this).parents("ul:first").find("li").removeClass("active");
		
		$(this).addClass("active");
		$(this).parents("li:first").addClass("active");
		
		var key = $(this).attr("rel").split("|")[0];
		var val = $(this).attr("rel").split("|")[1];
		
		var box = $(this).parents("div.small_box:first");
		
		box.find("input[name='"+key+"']").val(val);
	
		if (key != "page") {
			box.find("input[name='page']").val("1");
		}		
		
		box.find("form:first").ajaxSubmit({
			success: function(responseText, statusText) {
				 box.find(".target:first").html(responseText).show();
				 // makeSmallTabs();
			}
		});
		
		$(this).blur();
		return false;
	});
}

function makeTabsForLevelBrowser() {
	var box = $("#game-levels");
	$("ul.level_browser_tabs a", box).click(function() {
		$(this).parents("ul:first").find("a").removeClass("active");
		$(this).parents("ul:first").find("li").removeClass("active");
		
		$(this).addClass("active");
		$(this).parents("li.auto_size:first").addClass("active");
		
		var key = $(this).attr("rel").split("|")[0];
		var val = $(this).attr("rel").split("|")[1];
		
		if (isClickOnTabs(this)) {
			clearAllFilters();
		}
		
		// set the value from the tab-rel property
		box.find("input[name='"+key+"']").val(val);
		
		if (val != "SINGLE") {
			box.find("input[name='levelId']").val(0);
			box.find("input[name='levelIndex']").val(0);
		}
		
		if (key != "page") {
			box.find("input[name='page']").val("1");
		}
		
		// alert(getNumberOfActiveFilters());
		
		if (!$("#findLevelsTab").hasClass("active") || $("#findLevelsTab").hasClass("active") && getNumberOfActiveFilters() > 0) {
			box.find("form:first").ajaxSubmit({
				success: function(responseText, statusText) {
					 $("div.target", box).html(responseText).show();
					 makeSelects();
					 makeSmallTabs();
				}
			});
		}
		
		$(this).blur();
		return false;
	});
}

function clearAllFilters() {
	var box = $("#game-levels");
	$("#active_level_filters").empty();
	$("table.find_filters", box).find("a.active").removeClass("active");
	$("#liveLevelSearch").val("");
	box.find("input[name='difficulty']").val("0");
	box.find("input[name='search']").val("");
	$("#selected_level_tags").empty();
	$("#selected_levelFilters").empty();
	checkActiveFilters();
}

function isClickOnFindTab(obj) {
	return isClickOnTabs(obj) && $(obj).attr("id") == "findLevelsTab";
}

function isClickOnTabs(obj) {
	return !$(obj).parents("ul:first").hasClass("views_switch_3");
}

function toggleBoxes() {
	var headers = $("div.box > div.header");
	
	$("a.switch", headers).each(function() {
		$(this).click(function() {
			var box = $(this).parents("div.box:first");
			// load content				
			box.find(".target:first:empty").each(function() { loadBoxContent(box); });
			
			if (box.find("a.switch:first").hasClass("expanded")) {
				// box is open
				box.find(".previous_next").hide();
			} else if (box.find(".previous_next").length != 0 ) {
				loadBoxContent(box);
			}
			
			// toggle content
			box.find(".content").toggle();

			box.find("a.switch:first").toggleClass("expanded").toggleClass("collapsed");
			
			// $('html, body').animate({scrollTop: ($(this).offset().top - 25)}, 1000);
			
			$(this).blur();
			return false;
		});
		$(this).dblclick(function() {
			refreshBox(this);
			return false;
		});
	});
}

function refreshBox(obj) {
	var box = $(obj).parents("div.box:first");
	loadBoxContent(box);
	$(obj).blur();
	return false;	
}

function changeAndLoadBox(obj, key, val, fn) {
	var box = $(obj).parents("div.box:first");
	box.find("input[name='"+key+"']").val(val);
	if (key != "page") {
		box.find("input[name='page']").val("1");
	}		
	loadBoxContent(box, fn);
}

function changeAndLoadSmallBox(obj, key, val) {
	var box = $(obj).parents("div.small_box:first");

	box.find("input[name='"+key+"']").val(val);
	
	if (key != "page") {
		box.find("input[name='page']").val("1");
	}		
	loadBoxContent(box);
}

function loadBoxContent(box, fn) {	
	var x = $(box); 
	x.find("form:first").ajaxSubmit({
		success: function(responseText, statusText) {
			 $(x).find(".target:first").html(responseText).show();
			 if (fn) fn();
		}
	});
}

function makeSlidingBoxes() {
	$(".sliding_box a.left").click(function() {
		var current = $(this).parents(".sliding_box").find(".current").text();
		var max = $(this).parents(".sliding_box").find(".max").text();
		var width = $(this).parents(".sliding_box").find("div.scrollable div.items div").width();
		current--;
		
		if (current == 0) {		
			current = max; 
		}
		
		$(this).parents(".sliding_box").find(".scrollable").animate({scrollLeft: (current - 1) * width}, 400);
		$(this).parents(".sliding_box").find(".current").html(current);
		
		$(this).blur();
		return false;
	});
	
	$(".sliding_box a.right").click(function() {
		var current = $(this).parents(".sliding_box").find(".current").text();
		var max = $(this).parents(".sliding_box").find(".max").text();
		var width = $(this).parents(".sliding_box").find("div.scrollable div.items div").width();
		
		if (current != max) {
			current++;
		} else {
			current = 1;
		}
		
		$(this).parents(".sliding_box").find(".scrollable").animate({scrollLeft: (current - 1) * width}, 400);
		$(this).parents(".sliding_box").find(".current").html(current);
		
		$(this).blur();
		return false;
	});	
}

//--------------------------------------------------------------------------------------------
// COMMENT

function voteUp(obj, commentId) {
	if (!currentUserCheck()) {
		return false;
	}
	$.get("/comment/voteUpComment.null", { commentId: commentId }, function(data) {
		$(obj).parents(".spam_vote:first").html(data);
	});
}

function voteDown(obj, commentId) {
	if (!currentUserCheck()) {
		return false;
	}
	$.get("/comment/voteDownComment.null", { commentId: commentId }, function(data) {
		$(obj).parents(".spam_vote:first").html(data);
	});
}

function confirmReportSpam(commentId) {
	Boxy.load("/comment/confirmReportSpam.null?commentId=" + commentId, {modal: true});
}

function reportSpam(obj, commentId) {
	if (!currentUserCheck()) {
		return false;
	}
	$("#spam_vote_" + commentId).load("/comment/reportSpam.null", { commentId: commentId });
	Boxy.get(obj).hideAndUnload();
}

function confirmDeleteComment(obj, commentId) {
	Boxy.load("/comment/confirmDeleteComment.null?commentId=" + commentId, {modal: true});
}

function deleteComment(obj, commentId) {
	$("#comment_" + commentId).load("/comment/deleteComment.null", { commentId: commentId });
	var container = $("#comment_"+commentId);
	
	var reply = container.next();
	if (container.hasClass("level_1") && $(reply).hasClass("reply_form_wrapper")) {
		$(reply).hide();
	}

	if (container.hasClass("level_1")) {
		container.removeClass("level_1").addClass("level_1_hidden");
	}
	else if (container.hasClass("level_2")) {
		container.removeClass("level_2").addClass("level_2_hidden");
	}
	
	
	Boxy.get(obj).hideAndUnload();
}

function showCommentReply(obj) {
	if (!currentUserCheck()) {
		return false;
	}
	$(obj).parents(".reply_form_wrapper:first").find(".post").show();
	$(obj).parents(".reply:first").hide();
}

function showBadQualityComment(obj) {
	$(obj).parents("div:first").find("dl").show();
	var container = $(obj).parents("div:first");
	
	if (container.hasClass("level_1_hidden")) {
		container.removeClass("level_1_hidden");
		container.addClass("level_1");
	}
	
	if (container.hasClass("level_2_hidden")) {
		container.removeClass("level_2_hidden");
		container.addClass("level_2");
	}
	
	$(obj).parents("p:first").remove();
}

//--------------------------------------------------------------------------------------------
// LEVEL

function rateLevel(theLevelId, status, obj) {
	if (!currentUserCheck()) {
		return false;
	}
	
	$('#loading-level-rating').show(); 
	$.get("/games/"+GAME_LINK+"/rateLevel.null", { levelId: theLevelId, rating: obj.title }, function(xml) {
		var totalRated = $(xml).find('total-rated').text();
		var averageRating = $(xml).find('average-rating').text();
		$("#level-total-rated-"+theLevelId).html(totalRated);
		$("#level-your-rating-"+theLevelId).html(", you: " + obj.title);
		$("#level-current-rating-"+theLevelId).css({ width: (17 * averageRating)+"px" });
		$('#loading-level-rating').hide();
	});
}

function rateLevelDifficulty(theLevelId, status, obj) {
	if (!currentUserCheck()) {
		return false;
	}
	
	$('#loading-level-diff-rating').show(); 
	$.get("/games/"+GAME_LINK+"/rateLevelDifficulty.null", { levelId: theLevelId, rating: $(obj).attr("rel") }, function(xml) {
		var totalRated = $(xml).find('total-rated').text();
		var averageRating = $(xml).find('average-rating').text();
		$("#level-difficulty-"+theLevelId).html(totalRated+" ratings, you: " + obj.title);
		$("#level-current-difficulty-"+theLevelId).css("left", (16*averageRating-16)+"px").css("background-position", -(16*averageRating-16)+"px -11px");
		$("#level-current-difficulty-"+theLevelId).text("Current difficulty: "+averageRating);
		$('#loading-level-diff-rating').hide(); 
	});
}

function addLevelFavorite(theLevelId) {
	if (!currentUserCheck()) {
		return false;
	}
	
	$.get('/games/'+GAME_LINK+'/addLevelFavorite.null', { levelId: theLevelId }, function(xml) {
    	var response = $(xml).find('status').text();
    	if (response == "OK") {
    		var timesFavored = $(xml).find('times-favored').text();
			var levelFans = timesFavored+" Fan";
			if(timesFavored > 1) levelFans += "s";
    		$("#level-fan-counter-"+theLevelId).html(levelFans);
    		$("#link-fan-"+theLevelId).html("<span class='link_fan_active'>You're a fan</span> <a href='#RemoveLevelFavorite' onclick='removeLevelFavorite("+theLevelId+");return false;'>(Quit)</a>");
			changeAndLoadSmallBox($("#level-fan-counter-"+theLevelId), "page", 1);
    	}
	}, 'xml');
}

function removeLevelFavorite(theLevelId) {
	$.get('/games/'+GAME_LINK+'/removeLevelFavorite.null', { levelId: theLevelId }, function(xml) {
    	var response = $(xml).find('status').text();
    	if (response == "OK") {
    		var timesFavored = $(xml).find('times-favored').text();
			var levelFans = timesFavored+" Fan";
			if(timesFavored > 1) levelFans += "s";
			$("#level-fan-counter-"+theLevelId).html(levelFans);
			$("#link-fan-"+theLevelId).html("<a href='#AddLevelFavorite' class='link_fan' onclick='addLevelFavorite("+theLevelId+");return false;'>Become a fan</a>");
			changeAndLoadSmallBox($("#level-fan-counter-"+theLevelId), "page", 1);
    	}
	}, 'xml');
}

//--------------------------------------------------------------------------------------------
// TOOLTIP

function tooltip(obj) {	
	if (!$(obj).data('tooltip')) {
		$(obj).data('tooltip','T');
		
		xOffset = 0;
		yOffset = -20;
		
		$(obj).hover(function(e) {											  
			showTooltip(obj);
	    }, function() {
			var t = $("#tooltip");
			t.fadeOut(300, function(){ $(t).remove() });
	    });
		
		$(obj).mousemove(function(e) {
			var top = $(obj).offset().top + yOffset;
			var left = $(obj).offset().left + $(obj).width() + xOffset;				
			$("#tooltip").css("top", top + "px").css("left", left + "px");
		});
	
		$(obj).trigger('mouseover');
	}
}

function showTooltip(obj) {
	
	$("#tooltip").remove();

	var params = $(obj).attr("rel").split("|");
	$("body").append("<div id='tooltip'>&nbsp;</div>");
	var callingTooltip = $("#tooltip")[0];
	
	setTimeout(function() {
		if ($("#tooltip").length > 0 && $("#tooltip")[0] == callingTooltip) {
			$("#tooltip").fadeIn("fast");
			$("#tooltip").load("/" + params[0] + "/tooltip.null", { value: params[1], size: params[2] });
		}
	}, 350);
}

function showQuickhelps() {
	var quickhelps = $("a.quickhelp");
	
	quickhelps.hover(function(e) {
		var text = $(this).find("span").html();
		$("body").append("<div id='tooltip' class='tooltip tooltip_big'><div class='tooltip_content'><p>"+text+"</p></div></div>");
		$("#tooltip").fadeIn("fast");
	}, function() {
		var t = $("#tooltip");
		t.fadeOut(300, function(){ $(t).remove() });
	});
	
	quickhelps.mousemove(function(e) {
		var obj = this;
		var top = $(obj).offset().top - 20;
		var left = $(obj).offset().left + $(obj).width() + 10;				
		$("#tooltip").css("top", top + "px").css("left", left + "px");
	});
	
}

// ----------------------------------------------------------------------------
// DEV CENTER

function logout(isFacebookUser) {
	var loggedOut = false;
	
	var endSession = function() {
		$.get("/j_spring_security_logout", {}, function(html) {
			loggedOut = true;
			// do this after launch: window.location.reload();
			window.location = "/";
		});
	}
	
	window.setTimeout(function() {
		if (!loggedOut) {
			endSession();
		}
	}, 2000);
	
	return false;
}

function createCompanyDialogButton(user) {
	$("#found-company-button").click(function() {
		if (user != "") {
			Boxy.load("/devcenter/newCompany.null", {modal: true});
		} else {
			alert("Please log in or sign up first!");
		}
		return false;		
	});
}

function createGameDialogButton(developerName) {
	$(".new-game-button").click(function() {
		var url = '/devcenter/newGame.null';
		if (developerName){
			url += "?developerName=" + developerName;
		}
		Boxy.load(url, { 
		modal: true, 
		afterShow: function() {
			makeSelects();
		} });
		return false;
	});
}

function checkCharacter(event) {
	var code = (event.which == null) ? event.keyCode : event.which;

	if (code == 8 || code == 0) {
		return true;
	}
	
	var allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789_";
	return allowed.indexOf(String.fromCharCode(code)) >= 0;
}

function checkTagCharacter(event) {
	var code = (event.which == null) ? event.keyCode : event.which;
	if (code == 8 || code == 0) {
		return true;
	}	
	var allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789_.-#+*~!,;:|";
	return allowed.indexOf(String.fromCharCode(code)) >= 0;
}

function checkNumber(event) {
	var code = (event.which == null) ? event.keyCode : event.which;
	if (code == 8 || code == 0) {
		return true;
	}	
	var allowed = "0123456789";
	return allowed.indexOf(String.fromCharCode(code)) >= 0;	
}

// ----------------------------------------------------------------------------

jQuery.fn.appendDom = function(template) {
  return this.each(function() {
    for (element in template) {
      var el = (typeof(template[element].tagName) === 'string') ?
        document.createElement(template[element].tagName): document.createTextNode('');
      delete template[element].tagName;
      for (attrib in template[element]) {
        switch ( typeof(template[element][attrib]) ) {
          case 'string' :
            if ( typeof(el[attrib]) === 'string' ) {          
             el[attrib] = template[element][attrib];
            } else {
              el.setAttribute(attrib, template[element][attrib]);
            }
            break;
          case 'function':
            el[attrib] = template[element][attrib];
            break;
          case 'object' :
            if (attrib === 'childNodes')  {$(el).appendDom(template[element][attrib]);}
            break;
        }
      }
      this.appendChild(el);
    }
  });
};

// ----------------------------------------------------------------------------

jQuery.fn.truncate = function(options) {    
  var defaults = {  
   length: 300,  
   minTrail: 20,  
   moreText: "more...",  
   lessText: "less...",  
   ellipsisText: " "  
  };  
    
  var options = $.extend(defaults, options);  
      
  return this.each(function() {  
   obj = $(this);  
   var body = obj.html();  
     
   if(body.length > options.length + options.minTrail) {  
    var splitLocation = body.indexOf(' ', options.length);  
    if(splitLocation != -1) {  
     // truncate tip  
     var splitLocation = body.indexOf(' ', options.length);  
     var str1 = body.substring(0, splitLocation);  
     var str2 = body.substring(splitLocation, body.length);
     obj.html(str1 + '<span class="truncate_ellipsis">' + options.ellipsisText +   
      '</span>' + '<span  class="truncate_more">' + str2 + '</span>');  
     obj.find('.truncate_more').css("display", "none");  
       
     // insert more link  
     obj.append(  
      '<span>' +  
       ' <a href="#" class="truncate_more_link">' +  options.moreText + '</a>' +   
      '</span>'  
     );  
  
     // set onclick event for more/less link  
     var moreLink = $('.truncate_more_link', obj);  
     var moreContent = $('.truncate_more', obj);  
     var ellipsis = $('.truncate_ellipsis', obj);  
     moreLink.click(function() {  
      if(moreLink.text() == options.moreText) {  
       moreContent.fadeIn(300); 
	   
       moreLink.text(options.lessText);  
       ellipsis.css("display", "none");  
      } else {  
       moreContent.fadeOut(300);  
       moreLink.text(options.moreText);  
       ellipsis.css("display", "inline");  
      }  
      return false;  
       });  
    }  
   } // end if  
  });  
 };
 
// ----------------------------------------------------------------------------
 
 jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); 
            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(); // use expires attribute, max-age is not supported by IE
        }
        
        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;
    }
};

// ----------------------------------------------------------------------------

function clearSearch(obj){
	var searchField = $(obj).prev("input:first");
	searchField.val("");
	if ($("input[name='search']").length > 0) {
		changeAndLoadBox(obj, "search", "");
	}
}

//--------------------------------------------------------------------------------------------
// FACEBOOK

function onFacebookLogin(obj) {
	
	// check logged in 
	
	FB.ensureInit(function () {
		//facebook_onload(true);
		obj.parents(".boxy-inner").load('/facebook/isPlatogoUser.null', null);
	});
}

function loginOrNewFacebookUser() {
	FB.ensureInit(function () {
		//facebook_onload(true);
		Boxy.load('/facebook/isPlatogoUser.null', {
			modal: true
		});
	});
}

function connectWithFacebookLandingPage() {
	promptPermission(onFacebookLandingPagePermissionRequested);
}

function onFacebookLandingPagePermissionRequested(permissionString) {
	
	var notificationPermission = false;
	var favorPermission = false;
	var createLevelPermission = false;
	
	if (permissionString.match("email")) {
		notificationPermission = true;
	}

	if (permissionString.match("publish_stream")) {
		favorPermission = true;
		createLevelPermission = true;
	}
	
	$.get('/facebook/connectExistingPlatogoUserWithFacebookFromLandingpage.null', { notificationPermission: notificationPermission, favorPermission: favorPermission, createLevelPermission: createLevelPermission }, function(xml) {
			if ($(xml).find("status").text() != 'OK') {
				Boxy.load("/facebook/showFacebookError.null", { modal: true });		
			} else {
				Boxy.load("/facebook/showConfirmation.null", { modal: true });
			}
			
		}, 'xml');
}

function connectWithFacebook(obj) {
	// first request permissions
	promptPermission(onPermissionsRequested);
}

function promptPermission(callback) {
	facebook_prompt_permission("publish_stream", callback);
}

function onPermissionsRequested(permissionString) {
	
	var notificationPermission = false;
	var favorPermission = false;
	var createLevelPermission = false;
	
	if (permissionString.match("email")) {
		notificationPermission = true;
	}

	if (permissionString.match("publish_stream")) {
		favorPermission = true;
		createLevelPermission = true;
	}
	
	var box = $("#facebookTab").find("div.target");
	box.load('/facebook/connectExistingPlatogoUserWithFacebook.null', {notificationPermission:notificationPermission, favorPermission:favorPermission, createLevelPermission:createLevelPermission}, function() {
		Boxy.get(box).hideAndUnload();
		Boxy.load("/facebook/showConfirmation.null", { modal : true });
	});
}

function disconnectFacebookUser(obj) {
	var box = $(obj).parents("div.target");
	box.load('/facebook/disconnectPlatogoUser.null', null, function(xml) {
		//find close buttons and rewrite action to refresh
		var popUp = $("#pop_edit_user_profile");
		popUp.find("p.pop_close a").click(refresh_page);
		popUp.find("div.footer p.cancel a").click(refresh_page);
	});
}

function disableFacebookUser(obj) {
	var box = $(obj).parents("div.target");
	box.load('/facebook/disableFacebookApplicationUser.null', null, function(xml) {
		//find close buttons and rewrite action to refresh
		var popUp = $("#pop_edit_user_profile");
		popUp.find("p.pop_close a").click(refresh_page);
		popUp.find("div.footer p.cancel a").click(refresh_page);
	});
}

function renderXFBML() {
	FB_RequireFeatures(["XFBML"], function() {
	  FB.XFBML.Host.parseDomTree();
	  window.renderFacebookXFBML = false;
    });
}

// --------------------------------------------------------------------------------
// CONTEST

Date.prototype.getWeek = function() {
	var onejan = new Date(this.getFullYear(),0,1);
	return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
} 
	
function getStartOfNextContest(weekNo){
	var date = new Date();
	daysSinceLastMonday = eval(date.getDay()- 1);
	date.setDate(date.getDate() - daysSinceLastMonday);
	var weekNoToday = date.getWeek();
	var weeksDiff = eval(weekNo - weekNoToday + 1);
	date.setDate(date.getDate() + eval( 7 * weeksDiff ));
	date.setHours(0, 0, 0, 0);
	return date;
}