var dateExpirePersistentCookies=new Date().setTime(new Date()+(30*24*60*60*1000));


//Compare must take 2 jObject (jObj1,jObj2,opt)
//returning > 0 if jObj1 > jObj2 ; < 0 if jObj1 < jObj2
(function($)
{
	//{ "compare": similarityStringCompareText,"refStr": "Youzhny" }
	$.fn.extend({ min: function(opt)
	{
		var jMin=null;
		this.each(function()
		{
			var jThis=jQuery(this);
			if(jMin==null||opt.compare(jThis,jMin,opt)<0)
			{ jMin=jThis; }
		});
		return jMin;
	}
	});
})(jQuery);

function redirection(linkURL)
{
	jQuery(document).ready(function() { document.location.href=linkURL; });
	setTimeout("document.location.href='"+linkURL+"';",3000);
}
function RedirectTimezone()
{
	jQuery(document).ready(function() {
		//Silently add the tracking parameter to every single link in the page, much better than a redirection!
		if(!(document.location.href.indexOf("TimeZoneUTCOffset")>0) && !jQuery.cookie("TimeZone") && !jQuery.cookie("TimeZoneUTCOffset"))
		{
			var offset=-1*new Date().getTimezoneOffset()/60;
			jQuery.cookie("TimeZoneUTCOffset",offset,{ path: "/" });
		
			jQuery("a").each(function() {
				var href=this["href"];
				if(href && href.indexOf("http://")<0 && href.indexOf("javascript")<0 && href.indexOf("(")<0)
				{
					href=href+(href.indexOf("?")>=0?"&":"?")+"TimeZoneUTCOffset="+offset;
					this["href"]=href;
				}
			});
		}
	});
}

function launchSearch(searchBoxId,pageURL,DId,DId2,DId3,InviteUserId,QueryType)
{
	var query=URLEncode(jQuery("#"+searchBoxId).val());
	if(query)
	{
		var separator="?";
		if(pageURL.indexOf("?")>=0)
		{ separator="&"; }
		
		var url=pageURL+separator;
		if(DId)
		{url+="DId="+DId+"&";}
		if(DId2)
		{url+="DId2="+DId2+"&";}
		if(DId3)
		{url+="DId3="+DId3+"&";}
		if(InviteUserId)
		{url+="InviteUserId="+InviteUserId+"&";}
		document.location.href=url+"QueryType="+URLEncode(QueryType)+"&Query="+query;
	}
	return false;
}

/*
Not working cross browser :(
function autoResizeIframe(frameId,noAutoRecall)
{
	frame=jQuery("#"+frameId).get(0);
	if(frame)
	{
		innerDoc=(frame.contentDocument)?frame.contentDocument:frame.contentWindow.document;
		objToResize=(frame.style)?frame.style:frame;
		objToResize.height=innerDoc.body.scrollHeight+10;

		if(!noAutoRecall)
		{
			//Wait for the iframe to be loaded
			setTimeout(function()
			{ autoResizeIframe(frameId,true); },1000);
			setTimeout(function()
			{ autoResizeIframe(frameId,true); },2500);
			setTimeout(function()
			{ autoResizeIframe(frameId,true); },5000);
			setTimeout(function()
			{ autoResizeIframe(frameId,true); },10000);
		}
	}
}
*/

function registerHelp(controlId,helpId)
{
	var jControl=jQuery("#"+controlId);
	var jHelp=jQuery("#"+helpId);

	jControl.focus(function()
	{ jHelp.show(); });
	jControl.blur(function()
	{ setTimeout(function() { jHelp.hide(); },100); });
}

function requireIdentification()
{
	if(IdentificationId)
	{ return true; }
	if(confirm("You need to be registered and log in to do this. Do you want to sign up now?"))
	{ document.location.href="/Y/SignUp/"; }
	return false;
}

function getTrackingUrl(href,campaignTracking,utm_content)
{
	campaignTracking=campaignTracking.replace("{0}",utm_content);
	return href.replace("{0}",campaignTracking).replace("{1}",URLEncode(campaignTracking));
}

var haveFBVar=false;
var haveFBInitialized=false;
function haveFB()
{ return haveFBVar; }
function havePublished()
{ return jQuery.cookie("havePublishedFeed"); }
function setHavePublished()
{ return jQuery.cookie("havePublishedFeed","1",{ path: "/",expires: new Date().setTime(new Date()+(24*60*60*1000)) }); }
function initFB()
{
	if(!haveFB())
	{
		haveFBVar=true;

		window.fbAsyncInit=function() {
			FB.init({
				appId: fbConnectAppId,
				status: true,
				cookie: true,
				xfbml: true,
				oauth: true
			});
			haveFBInitialized=true;

			processWaitFB();
		};

		(function ()
		{
			var e=document.createElement("script");
			e.async=true;
			e.src="//connect.facebook.net/en_US/all.js";
			var fbRoot=document.getElementById("fb-root");
			if(fbRoot!=null)
			{ fbRoot.appendChild(e); }
		} ());
	}
}

var waitFBCallbacks=new Array();
function waitFB(callback)
{
	if(callback)
	{ waitFBCallbacks.push(callback); }
	processWaitFB();
}
function processWaitFB()
{
	if(haveFBInitialized)
	{
		var callback;
		while(callback=waitFBCallbacks.pop())
		{callback();}
	}
}

function retrieveExternals()
{
	initFB();
	waitFB(function ()
	{
		var uidsCalled=new Array();
		jQuery(".External_FACEBOOK").each(function ()
		{
			var uid=getObjClassId(this);

			if(!uidsCalled[uid])
			{
				uidsCalled[uid]=true;

				FB.api("/"+uid,function (uidInfos)
				{
					jQuery(".External_FACEBOOK.Id_"+uidInfos.id+".ExternalName").text(uidInfos.name);
					jQuery(".External_FACEBOOK.Id_"+uidInfos.id+".ExternalPicSquare").attr("src","http://graph.facebook.com/"+uidInfos.id+"/picture");
				});
			}
		});
	});
}

var currentUserUid;
var currentUserUidCallbacks;
function getCurrentUserUid(callback)
{
	if(currentUserUid)
	{
		callback(currentUserUid);
		return;
	}

	var askFacebook=false;
	if(!currentUserUidCallbacks)
	{
		currentUserUidCallbacks=new Observer;
		askFacebook=true; 
	}
	currentUserUidCallbacks.subscribe(callback);

	if(askFacebook)
	{
		initFB();
		waitFB(function()
		{
			FB.login(function(response)
			{
				if(response.authResponse)
				{
					currentUserUid=response.authResponse.userID;
					currentUserUidCallbacks.fire(currentUserUid);
					currentUserUidCallbacks=null;
				}
			});
		});
	}
}

var friendsFB=null;
function feedPublishRandomFriend(publishFunction,template_bundle_id,template_data,body_general,callback,user_message_prompt,user_message,forceEvenIfHaveAlreadyPublished,displayDialogIfPermissionDenied)
{
	waitFB(function ()
	{
		if(friendsFB==null)
		{
			getCurrentUserUid(function (uid)
			{
				var query=FB.Data.query("SELECT uid FROM user WHERE has_added_app=1 and uid IN (SELECT uid2 FROM friend WHERE uid1={0})",uid);
				query.wait(function (rows)
				{
					friendsFB=new Array();
					for(var i=0;i<rows.length;i++)
					{ friendsFB.push(rows[i].uid); }

					publishFunction(template_bundle_id,template_data,getRandomFriend(),body_general,callback,user_message_prompt,user_message,forceEvenIfHaveAlreadyPublished,displayDialogIfPermissionDenied);
				});
			});
		}
		else
		{ publishFunction(template_bundle_id,template_data,getRandomFriend(),body_general,callback,user_message_prompt,user_message,forceEvenIfHaveAlreadyPublished,displayDialogIfPermissionDenied); }
	});
}
function getRandomFriend()
{
	if(friendsFB!=null && friendsFB.length>0)
	{ return friendsFB[Math.round(Math.random()*friendsFB.length*10)%friendsFB.length]; }
	return null;
}
function feedPublishDialog(template_bundle_id,template_data,target_id,body_general,callback,user_message_prompt,user_message,forceEvenIfHaveAlreadyPublished)
{
	//This function needs to be rewritten
	return;

	if(haveFB())
	{
		if(forceEvenIfHaveAlreadyPublished||!havePublished())
		{
			var jUserMessage=new Object();
			jUserMessage.value=user_message;

			var targetObj=target_id?[target_id]:null;

			FB.ui({
				method: "stream.publish",
				message: user_message,
				attachment: {
					name: 'Connect',
					caption: 'The Facebook Connect JavaScript SDK',
					href: 'http://github.com/facebook/connect-js'
				},
				action_links: [
					{ text: 'Code',href: 'http://github.com/facebook/connect-js' }
				],
				user_prompt_message: 'Share your thoughts about Connect'
			},function(response)
			{
			
			});
			
			FB.Connect.showFeedDialog(template_bundle_id,template_data,targetObj,body_general,null,FB.RequireConnect.promptConnect,function()
			{
				if(callback)
				{ callback(result); }

				SafeTrackEvent("facebook-actions","publish-showFeedDialog-random","userId: "+UserId+";");
				return;
			},user_message_prompt,jUserMessage);
		}
	}
}
function feedPublishSilent(template_bundle_id,template_data,target_id,body_general,callback,user_message_prompt,user_message,forceEvenIfHaveAlreadyPublished,displayDialogIfPermissionDenied)
{
	//This function needs to be rewritten
	return;

	if(haveFB())
	{
		if(forceEvenIfHaveAlreadyPublished||!havePublished())
		{
			//Request publish_stream permission
			requestPermission("publish_stream",function(canStreamPublish)
			{
				setHavePublished();	//This is not transparent for the user (which can refuse), so it can disturb him.
				if(canStreamPublish)
				{
					var api=FB.Facebook.apiClient;
					api.friends_getAppUsers(function(target_ids)
					{
						if(!target_ids)
						{ target_ids=target_id?[target_id]:null; }

						//Requires the publish_stream permission which can only be granted to the stream whitelist
						api.feed_publishUserAction(template_bundle_id,template_data,target_ids,body_general,2,user_message,function(result,exception)
						{
							//alert(result);
							//alert(exception);
							if(callback)
							{ callback(result); }

							SafeTrackEvent("facebook-actions","publish-feed_publishUserAction","userId: "+UserId+";");
						});
					});
				}
				else if(displayDialogIfPermissionDenied)
				{ feedPublishDialog(template_bundle_id,template_data,target_id,body_general,callback,user_message_prompt,user_message,true); }
			});
		}
	}
}

function requestPermission(permissions,callback)
{
	waitFB(function ()
	{
		FB.login(function (response)
		{
			if(callback)
			{ callback(response); }
		},{ perms: permissions });
	});
}

function fbGetInfosByUid(uid,usersInfos)
{
	if(usersInfos)
	{
		for(var i=0;i<usersInfos.length;i++)
		{
			if(usersInfos[i].uid==uid)
			{ return usersInfos[i]; }
		}
	}
	return null;
}

function getPageArticles()
{
	var articles=new Array();
	var index=0;

	jQuery(".articleBox").each(function()
	{
		var article=new Object();
		var jThis=jQuery(this);

		var href=jThis.find("a").attr("href");
		href=href.startsWith("http://")?href:"http://oopad.com/"+href;

		var img=jThis.find("img").attr("src");
		img=img.startsWith("http://")?img:"http://oopad.com/"+img;
		articles[index]=article;
		index++;
	});
	if(articles.length==0)
	{ articles[0]={ "href": "http://oopad.com/Y/LogIn/FBConnect/","img": "http://oopad.com/Images/Logo.png" }; }
	return articles;
}

var toggledBoxes=new Array();
function toggleBox(jQueryPanelSelector,clickedObj)
{
	var jClickedObj=jQuery(clickedObj);
	var jPanel=jQuery(jQueryPanelSelector);
	var jParent=jClickedObj.closest("div");
	var show=!jPanel.is(":visible");
	if(show)
	{
		jPanel.slideDown("fast",function()
		{
			jParent.find(".show").hide();
			jParent.find(".hide").show();
		});
	}
	else
	{
		jPanel.slideUp("fast",function()
		{
			jParent.find(".show").show();
			jParent.find(".hide").hide();
		});
	}
	toggleBoxSave(jQueryPanelSelector,show);
	return false;
}
function toggleBoxSave(jQueryPanelSelector,hideOrShow)
{
	var hideOrShowBool=(hideOrShow!="hide" && hideOrShow)?1:0;
	toggledBoxes[jQueryPanelSelector]=hideOrShowBool;
	jQuery.cookie("toggledBoxes",ToQueryString(toggledBoxes));
}
function toggleBoxRestore()
{
	toggledBoxes=FromQueryString(jQuery.cookie("toggledBoxes"));
	for(var key in toggledBoxes)
	{
		if(toggledBoxes[key]>0)
		{jQuery(key).parent().find(".show").click();}
	}
}

var expand=new Array();
function expandSmallReply(box)
{
	if(IdentificationId)
	{
		if(!expand[box.id])
		{
			expand[box.id]=true;
			jQuery("#"+box.id+"_li .inputButton").removeClass("replyInvisible");
			jQuery("#"+box.id).autogrow({ });
		}
	}
	else
	{document.location.href="/Y/SignUp/";}
}
function reduceSmallReply(box)
{
	if(jQuery("#"+box.id).val()=="")
	{
		expand[box.id]=false;
		jQuery("#"+box.id+"_li .inputButton").addClass("replyInvisible");
	}
}

function setVisibleTab(tabsContainer,tabId,divId)
{
	//Make everybody inactive or invisible
	jQuery("#"+tabsContainer+" .tabs li").removeClass("active");
	jQuery("#"+tabsContainer+" .tabsPanel>div").each(function() { this.style.display="none"; });
	
	//Make the clicked tab active...
	jQuery("#"+tabId).addClass("active");
	//... and it's content visible
	//jQuery("#"+divId).each(function() { this.style.display=""; });
	jQuery("#"+divId).fadeIn("fast");
	
	SafeTrackEvent("tab-change","set-tab-in-"+tabsContainer,"tab: "+tabId+";");
}

parameterValueFromClassIdClicked=false;
function setParameterValueFromClassId(linkObj,parameterValue,normalHref,resetPageScroll,callback)
{
	parameterValueFromClassIdClicked=true;
	
	var jThis=jQuery(linkObj);
	var id=getObjClassId(linkObj);
	setHashValue(parameterValue,id);

	createGetToPostHiddenFields(normalHref,jQuery("input[name='PostBackKey']").closest("span"));
	jQuery("input[name='"+parameterValue+"']").val(id);

	if(resetPageScroll)
	{ window.scroll(0,0); }
	
	if(callback)
	{ return callback(linkObj,parameterValue,normalHref,resetPageScroll); }
	return true;
}
function restoreLinkButtonClickFromHash(hashParameterName,jContainer,clickAll)
{
	var id=getHashValue(hashParameterName);
	if(id)
	{
		var elements;
		if(clickAll)
		{ elements=jContainer.find("a"); }
		else
		{ elements=jContainer.find(".Id_"+id); }

		elements.each(function()
		{
			var jThis=jQuery(this);
			var href=jThis.attr("href");
			jThis.click();
			eval(href);
			return;
		});
	}
}

function setPercentValue(jParentObj,value)
{
	value=Math.round(value);
	value=Math.max(value,0);
	value=Math.min(value,100);
	
	var jValueObj=jParentObj.find(".percentValue");
	jValueObj.html(value+"%");
	jValueObj.animate({
		width: value+"%"
	},2000);
}

function updateStatus()
{
	var status=jQuery("#status").val();
	if(IdentificationId)
	{
		TGB.WebServices.BeterZ.UserWebService.SetStatus(IdentificationId,status,function(result){
			if(result)
			{highlightParentsAndDescendants(jQuery("#updateStatus").get(0));}
		},function(error){
			//alert(error.get_message());
		});
		SafeTrackEvent("update-status","update-status",status);
	}
	return false;
}

function highlightMarked(sender,args)
{jQuery.each(args.get_panelsUpdated(),function() { highlightParentsAndDescendants(this); });}
function highlightParentsAndDescendants(obj)
{
	if(obj && obj.id)
	{
		//Parents
		jQuery.each(jQuery(".highlightThis:has(#"+obj.id+")"),function() { highlight(this); });
		//Descendants
		jQuery.each(jQuery("#"+obj.id+" .highlightThis"),function() { highlight(this); });
	}
}
function highlight(obj)
{
	if(obj && obj.id)
	{
		setTimeout("jQuery('#"+obj.id+"').addClass('highlight');jQuery('#"+obj.id+"').removeClass('noHighlight');",0);
		setTimeout("jQuery('#"+obj.id+"').addClass('noHighlight');jQuery('#"+obj.id+"').removeClass('highlight');",100);
		setTimeout("jQuery('#"+obj.id+"').addClass('highlight');jQuery('#"+obj.id+"').removeClass('noHighlight');",200);
		setTimeout("jQuery('#"+obj.id+"').addClass('noHighlight');jQuery('#"+obj.id+"').removeClass('highlight');",300);
		setTimeout("jQuery('#"+obj.id+"').addClass('highlight');jQuery('#"+obj.id+"').removeClass('noHighlight');",400);
		setTimeout("jQuery('#"+obj.id+"').addClass('noHighlight');jQuery('#"+obj.id+"').removeClass('highlight');",500);
	}
}
function activeParentsAndDescendants(obj)
{
	if(obj && obj.id)
	{
		//Parents
		jQuery(".activeThis:has(#"+obj.id+")").addClass("active");
		//Descendants
		jQuery("#"+obj.id+" .activeThis").addClass("active");
	}
}
function desactiveParentsAndDescendants(obj)
{
	if(obj && obj.id)
	{
		//Parents
		jQuery(".activeThis:has(#"+obj.id+")").removeClass("active");
		//Descendants
		jQuery("#"+obj.id+" .activeThis").removeClass("active");
	}
}

/* ENABLE ROLLOVER ON TARGETED IMAGES/INPUT:IMAGE (ALL BROWSERS) */
function imgRollover(elt)
{
	//Replace, in the image SRC attribute, "-off" by "-on" when rolling over and then back "-on" by "-off"
    jQuery(elt).each(function() { jQuery(this).hover(function() { jQuery(this).attr("src",jQuery(this).attr("src").replace("-off","-on")); }, function () { jQuery(this).attr("src",jQuery(this).attr("src").replace("-on","-off")); }); } );
}

var slidingElements=new Array();
var filledElements=new Array();
function slide(callingImage,imgSrcUp,imgSrcDown,imgSrcWait,webService,webMethod,webMethodParameters)
{
	var divId=callingImage.id+"_div";
	
	if(!slidingElements[callingImage.id])
	{slidingElements[callingImage.id]="up";}
	
	switch(slidingElements[callingImage.id])
	{
		case "down":
			jQuery("#"+divId).slideUp("normal",function() { callingImage.src=imgSrcUp; slidingElements[callingImage.id]="up"; desactiveParentsAndDescendants(jQuery("#"+divId).get(0)); });
			break;
		default:
			var context=new Array(callingImage,divId,imgSrcUp,imgSrcDown);
			if(filledElements[divId])
			{SlideDownHTML("",context);}
			else
			{
				eval(webService+"."+webMethod+"("+webMethodParameters+",SlideSuccededCallback,SlideFailedCallback,context)");
				callingImage.src=imgSrcWait;
				slidingElements[callingImage.id]="down";
				SafeTrackEvent("webservice-call",webService+"."+webMethod,"fromImage: "+callingImage.id+";");
			}
			break;
	}
}
function SlideSuccededCallback(result,context)
{
	if(!result)
	{result="Nothing :(";}
	var callingImage=context[0];
	var divId=context[1];
	var imgSrcUp=context[2];
	var imgSrcDown=context[3];

	var html="";
	if(result.length && typeof(result)=="object")
	{
		//result is a string array
		html="<ul>";
		for(var i=0;i<result.length;i++)
		{html+="<li>"+result[i]+"</li>";}
		html+="</ul>";
	}
	else
	{
		//feed is a string
		html=result;
	}
	
	filledElements[divId]=true;
	SlideDownHTML(html,context);
	initCommonThings();
}
function SlideFailedCallback(error,context)
{
	html="Sorry, an error occured. Please check your network connection a try again. The returned error was: "+error.get_message();
	SlideDownHTML(html,context);
}
function SlideDownHTML(html,context)
{
	var callingImage=context[0];
	var divId=context[1];
	var imgSrcUp=context[2];
	var imgSrcDown=context[3];
	
	if(html)
	{jQuery("#"+divId).html(html);}
	jQuery("#"+divId).slideDown("fast",function() { callingImage.src=imgSrcDown; slidingElements[callingImage.id]="down"; activeParentsAndDescendants(jQuery("#"+divId).get(0)); });
}

var sports;
function initSports(callback)
{
	var req={
		"SessionKey": IdentificationId,
		"Locale": Locale
	};
	TGB.WebServices.BeterZ.Public.v1_0.PublicWebService.GetSports(req,function(resp)
	{
		sports=resp.Sports;
		if(callback)
		{ callback(); }
	},function(err)
	{
		debug(err.get_message());
		if(callback)
		{ callback(); }
	});
}

function getSportsName(sportsId)
{
	var str="";
	if(sportsId)
	{
		for(var i=0;i<sportsId.length;i++)
		{
			if(str)
			{ str+=", "; }
			str+=getSport(sportsId[i]).Name;
		}
	}
	return str;
}
function getSport(sportId)
{
	for(var i=0;i<sports.length;i++)
	{
		if(sports[i].Id==sportId)
		{ return sports[i]; }
	}
}

var followedThings=new Array();
var followedEvents,followedPersons;
function preInitFollowing()
{
	if(IdentificationId)
	{
		followedEvents=jQuery.cookie("followedEvents"+hex_sha1(IdentificationId));
		followedPersons=jQuery.cookie("followedPersons"+hex_sha1(IdentificationId));
		
		if(followedEvents==null && followedPersons==null)
		{
			//Can't follow events for the moment
			//TGB.WebServices.BeterZ.FollowsWebService.GetFollowedEvents(IdentificationId,succeedFollowing,failedFollowing,"followedEvents");
			TGB.WebServices.BeterZ.FollowsWebService.GetFollowedUsers(IdentificationId,succeedFollowing,failedFollowing,"followedPersons");
			//SafeTrackEvent("webservice-call","FollowsWebService.GetFollowedEvents");
			SafeTrackEvent("webservice-call","FollowsWebService.GetFollowedUsers");
		}
	}
}
function succeedFollowing(result,context)
{
	if(IdentificationId)
	{
		var stringTmp=createString(result);
		eval(context+"=stringTmp;");
		jQuery.cookie(context+hex_sha1(IdentificationId),stringTmp,{ path: "/" });
		initFollowing();
	}
}
function failedFollowing(error,context)
{/*alert(error.get_message());*/}
function initFollowing()
{
	//Activate followed things (new appeared things can be followed...)
	var arrTmp;
	arrTmp=getIds(followedEvents);
	for(var i=0;i<arrTmp.length;i++)
	{
		followedThings["("+arrTmp[i]+",0)"]=true;
		ActivateImageFollow(arrTmp[i],0);
	}
	
	arrTmp=getIds(followedPersons);
	for(var i=0;i<arrTmp.length;i++)
	{
		followedThings["(0,"+arrTmp[i]+")"]=true;
		ActivateImageFollow(0,arrTmp[i]);
	}
	
	//Add the javascript to the following images
	String.prototype.startsWith=function(t,i) { if(i==false) { return (t == this.substring(0, t.length)); } else { return (t.toLowerCase()==this.substring(0,t.length).toLowerCase()); } }
	jQuery(".followThis").each(function()
	{
		var eventId=0,personId=0;
		var classes=this.className.split(" ");
		for(var i=0;i<classes.length;i++)
		{
			if(classes[i])
			{
				var currentClass=classes[i].trim();
				if(currentClass)
				{
					var elements=currentClass.split("_");

					if(currentClass.startsWith("followPerson_"))
					{ personId=elements[1]; }
					else if(currentClass.startsWith("followEvent_"))
					{ eventId=elements[1]; }

					if(eventId>0||personId>0)
					{ break; }
				}
			}
		}
		if(eventId>0||personId>0)
		{
			jQuery(this).click(function()
			{ toggleFollowing(eventId,personId); });
		}
	});
}
function toggleFollowing(eventId,personId)
{
	if(IdentificationId)
	{
		if(eventId || personId)
		{
			var startOrStop="start";
			if(followedThings["("+eventId+","+personId+")"])
			{startOrStop="stop";}
			
			var context=new Array(startOrStop,eventId,personId);
			eval("TGB.WebServices.BeterZ.FollowsWebService."+(startOrStop=="start"?"Start":"Stop")+"Following(IdentificationId,personId>0?personId:null,eventId>0?eventId:null,FollowSuccededCallback,FollowFailedCallback,context);");
			SafeTrackEvent("webservice-call","FollowsWebService."+(startOrStop=="start"?"Start":"Stop")+"Following","personId: "+personId+"; eventId: "+eventId+";");
		}
	}
	else
	{ document.location.href="/Y/SignUp/"; }
	return false;
}
function FollowSuccededCallback(result,context)
{
	if(result)
	{
		var eventId=context[1],personId=context[2];
		if(context[0]=="start")
		{
			if(eventId && eventId>0 && IdentificationId)
			{
				TGB.WebServices.BeterZ.FollowsWebService.GetFollowedEventsNoCache(IdentificationId,succeedFollowing,failedFollowing,"followedEvents");	//Following an event might start following others
				SafeTrackEvent("webservice-call","FollowsWebService.GetFollowedEventsNoCache");
			}	
			else
			{ActivateImageFollow(eventId,personId);}
		}
		else
		{DisableImageFollow(eventId,personId);}
	}
}
function FollowFailedCallback(error,context)
{/*alert(error.get_message());*/}
function ActivateImageFollow(eventId,personId)
{
	if(eventId>0)
	{followedEvents=addIdToString(followedEvents,eventId);}
	if(personId>0)
	{followedPersons=addIdToString(followedPersons,personId);}
	followedThings["("+eventId+","+personId+")"]=true;
	SetImageFollow(eventId,personId,"on");
}
function DisableImageFollow(eventId,personId)
{
	if(eventId>0)
	{followedEvents=removeIdToString(followedEvents,eventId);}
	if(personId>0)
	{followedPersons=removeIdToString(followedPersons,personId);}
	followedThings["("+eventId+","+personId+")"]=false;
	SetImageFollow(eventId,personId,"off");
}
function SetImageFollow(eventId,personId,image)
{
	var from="-on",to="-off";
	if(image=="on")
	{from="-off";to="-on";}
	
	if(eventId>0)
	{
		jQuery(".followEvent_"+eventId+" img").each(function() { this.src=this.src.replace(from,to); });
		jQuery.cookie("followedEvents"+hex_sha1(IdentificationId),followedEvents,{ path: "/" });
		if(to=="-off")
		{jQuery(".removeThingsStopFollowed .followBox:has(.followEvent_"+eventId+")").fadeOut();}
	}
	if(personId>0)
	{
		jQuery(".followPerson_"+personId+" img").each(function() { this.src=this.src.replace(from,to); });
		jQuery.cookie("followedPersons"+hex_sha1(IdentificationId),followedPersons,{ path: "/" });
	}
}

function updateWalletAmount(walletId,currencyId)
{
	TGB.WebServices.BeterZ.UserWebService.GetWalletAmount(IdentificationId,walletId,function(result)
	{
		jQuery(".PlaceHolder.Wallet_Amount.WalletId_"+walletId).html(result.Amount);
		jQuery(".PlaceHolder.Wallet_Amount.WalletId_"+walletId+".FormatPrint").text(formatNumber(Math.floor(result.Amount*100)/100,2));

		var amountInPlay=Math.floor(result.AmountInPlay*100)/100;
		jQuery(".PlaceHolder.Wallet_AmountInPlay.WalletId_"+walletId+".FormatPrint").text(amountInPlay>0?("+ "+formatNumber(amountInPlay,2)):"");
	});
	SafeTrackEvent("webservice-call","UserWebService.GetWalletAmount","currency: "+currencyId+";");
}
function getPageWalletAmount(walletId)
{ return parseFloat(jQuery(".PlaceHolder.Wallet_Amount.WalletId_"+walletId+":not(.FormatPrint)").html()); }

function getWalletById(walletId)
{ return Wallets[walletId]; }
function getWalletByCurrencyId(currencyId)
{
	var walletFound={ Id: 0,CurrencyId: currencyId,Amount: 0,AmountInPlay: 0 };
	for(var walletId in Wallets)
	{
		var wallet=Wallets[walletId];
		if(wallet.CurrencyId==currencyId)
		{
			walletFound.Id=wallet.Id;
			walletFound.Amount+=wallet.Amount;
			walletFound.AmountInPlay+=wallet.AmountInPlay;
		}
	}
	
	return walletFound;
}
function getWalletHTML(wallet,symbol)
{
	if(wallet)
	{
		var str="";
		str+="<span class=\"PlaceHolder Wallet_Amount WalletId_"+wallet.Id+" CurrencyId_"+wallet.CurrencyId+" FormatPrint\">"+formatNumber(Math.floor(wallet.Amount*100)/100,2)+"</span> "+symbol;
		str+="<span class=\"PlaceHolder Wallet_Amount WalletId_"+wallet.Id+" CurrencyId_"+wallet.CurrencyId+" displayNone\">"+wallet.Amount+"</span>";
		str+="<br />";
		var amountInPlay=Math.floor(wallet.AmountInPlay*100)/100;
		str+="<span class=\"PlaceHolder Wallet_AmountInPlay WalletId_"+wallet.Id+" CurrencyId_"+wallet.CurrencyId+" FormatPrint\" title=\"Amount in play\">"+(amountInPlay>0?"+ "+formatNumber(amountInPlay,2):"")+"</span>";
		return str;
	}
	return "";
}

/* steps */
var stepWidths=new Array();
var currentSteps=new Array();
function initSteps()
{
	jQuery(".stepContainer").each(function(){
		var width=jQuery(".stepsNoOverflow:has(#"+this.id+")").width();
		stepWidths[this.id]=width;
		jQuery("#"+this.id+" > .step").css("width",width+"px");
		jQuery("#"+this.id+" > .step").css("vertical-align","top");
		
		var numberOfSteps=getNumberOfSteps(this.id);
		jQuery(this).css("width",Math.round(numberOfSteps*2*width)+"px");	//make it larger than it's content
	});
}

function cancelSteps(divId)
{
	//Call me on the .stepContainer
	jQuery("#"+divId+" > .step").css("width","100%");
	jQuery("#"+divId).css("width","100%");
}

function slideStep(divId,step)
{
	var offsetLeft=(1-step)*stepWidths[divId];
	currentSteps[divId]=step;
	var numberOfSteps=getNumberOfSteps(divId);
	var nextStepAnchor="#Step"+((step%numberOfSteps)+1);
	
	jQuery("#"+divId).animate({
		marginLeft: offsetLeft+"px"
	});
}

function nextStep(divId)
{
	var numberOfSteps=getNumberOfSteps(divId);
	var newStep=(currentStep%numberOfSteps)+1;
	slideStep(divId,newStep);
}

function getNumberOfSteps(containerId)
{return jQuery("#"+containerId+" > .step").size();}

function showDialog(jBox,options)
{
	jBox.dialog(jQuery.extend({
		hide: "highlight",
		close: function(event,ui)
		{ jQuery(this).dialog("destroy"); } 
	},options));
}

var currentAnchorStep=null;  
function checkAnchorStep(prefix,divId,hash,slideStepFunction)
{
	if(!hash)
	{ hash=document.location.hash; }
	
	
	if(currentAnchorStep!=hash)
	{
		currentAnchorStep=hash;
		var query=currentAnchorStep;
		if(!query)
		{query="#"+prefix+"1";}
		
		var step=query.replace("#"+prefix,"");
		if(!isNaN(step))
		{
			if(!slideStepFunction)
			{slideStepFunction=slideStep;}
			slideStepFunction(divId,step);
		}
	}
}

function initHeaderTab(elementId)
{
	var elt="#"+elementId;
	jQuery(elt).hover(function(){ jQuery(elt+" ul").fadeIn("fast"); },function() {});
	jQuery(elt+" ul").hover(function() {},function() { jQuery(elt+" ul").fadeOut("fast"); });
	jQuery(document).click(function() { jQuery(elt+" ul").fadeOut("fast"); });
}

/* Betting options */
var optionsValues=new Array("#advancedBetting");
function initOptions()
{
	for(var i=0;i<optionsValues.length;i++)
	{
		var cookieVal=jQuery.cookie("options_"+i);
		if(cookieVal>0 || cookieVal==null)
		{ jQuery(optionsValues[i]).each(function(){ this.checked = true; }); }
		jQuery(optionsValues[i]).click(function() { saveOptions(); });
	}
}

function saveOptions()
{
	applyOptions();
	for(var i=0;i<optionsValues.length;i++)
	{jQuery.cookie("options_"+i,jQuery(optionsValues[i]).is(":checked")?1:0,{ path: "/", expires: dateExpirePersistentCookies });}
}

function applyOptions()
{
	for(var i=0;i<optionsValues.length;i++)
	{
		var isChecked=jQuery(optionsValues[i]).is(":checked");
		switch(optionsValues[i])
		{
			case "#advancedBetting":
				if(isChecked)
				{
					jQuery(".backCol").removeClass("backColInvisible");
					jQuery(".layCol").removeClass("layColInvisible");
					//Prevent unbouncing users
					setTimeout("SafeTrackEvent('apply-option','advancedBetting','true',60)",60000);
				}
				else
				{
					jQuery(".backCol").addClass("backColInvisible");
					jQuery(".layCol").addClass("layColInvisible");
					//Prevent unbouncing users
					setTimeout("SafeTrackEvent('apply-option','advancedBetting','false',60)",60000);
				}
				break;
		}
	}
}

function makeTextareasAdaptatives()
{
	jQuery("textarea:not(.html):not(.replyBox):not(.noAutoGrow)").autogrow({});
}
function makeRoundings()
{
	//Round inside tabs
	jQuery("div.insideTabs").wrap("<div class=\"insideTabsBorder\"></div>");
	jQuery(".insideTabs").corner("round 5px").parent().css("padding","1px").corner("round 6px");
}

function updatePanelLoaded(sender,args)
{
	initCommonThings();
	//highlightMarked(sender,args);
}

function initHelpBoxes()
{
	jQuery(".helpBox").each(function()
	{
		//Initialize dialogs
		var jThis=jQuery(this);
		var jBox=jThis.find(".dialog").dialog({
			hide: "highlight",
			autoOpen: false
		});
		//Save the jBox into the jThis datas as we will need the object to open it...
		jThis.data("jBox",jBox);
	}).mouseover(function()
	{
		var position=getPosition(this);
		jQuery(this).data("jBox").dialog("option","position",[position.x+10,position.y-60]).dialog("open");
	}).mouseout(function()
	{ jQuery(this).data("jBox").dialog("close"); });

}

function initCommonThings()
{
	//Add alt class to tr and ul
	jQuery("table.alternable tbody tr:even,tr.alternable:even,ul.alternable li:even").addClass("alt");
	//jQuery("table.alternable tbody tr:odd,ul.alternable li:odd,tr.alternable:odd").removeClass("alt");
	
	//Filter numeric inputs
	jQuery("input.uint").autotab({ format: "numeric" });
	//jQuery("input.int").autotab({ format: "custom", pattern: "[^0-9\-]+" });
	//jQuery("input.double").autotab({ format: "custom", pattern: "[^0-9\.,]+" });
	//jQuery("input.alphanum").autotab({ format: "alphanumeric" });
	
	//Add up/down buttons, avoid updowning them twice or more when this function is reexecuted
	/*NB
	jQuery("input.odd:not(.upDowned):not(.template)").spin( {max: 1000, min: 1, imageBasePath: "/Images/Spin/",incrementFunction: Increase,decrementFunction: Decrease } );
	jQuery("input.odd:not(.template)").addClass("upDowned");
	jQuery("input.amount:not(.upDowned):not(.template)").spin( {min: 1, imageBasePath: "/Images/Spin/",incrementFunction: Increase,decrementFunction: Decrease } );
	jQuery("input.amount:not(.template)").addClass("upDowned");
	jQuery("input.upDown:not(.upDowned):not(.template)").spin( { imageBasePath: "/Images/Spin/" } );
	jQuery("input.upDown:not(.template)").addClass("upDowned");*/
	
	//jQuery(".disappear").fadeOut("slow");
	
	//initSteps();
	
	//applyOptions();
	//initFollowing();
}

//Highslide initialization
if(window.hs!=undefined)
{
	hs.graphicsDir="/Images/Highslide/";

	hs.Expander.prototype.onBeforeExpand=function()
	{ jQuery("object").hide(); };
	hs.Expander.prototype.onAfterClose=function()
	{ jQuery("object").show(); };
}

