var isBrowse = false;
$(document).ready(function(){
    if($("#isBrowse").val() == 1)
    {
        isBrowse = true;
    }
    
    $(".lazyLoad").lazyLoadAd() ;
   
   SetUpModalPopup();
   SetAutoExpand();
   if(isBrowse == false)
   {
        LoadOnlineTeams();
   } 
   else
   {
        LoadAllTeams();
   }
});

$(window).bind('load', function () {
    
    SetUpSelectMenues();
   // ShowRightSide();
    SetUpHoverImages();
    PreloadAll();
    SetUpNewsBar();
    
    SetAutoComplete();
    
   if(!isBrowse)
   {
        LoadOnlineTeams();
   } 
   
    ShowMain();
});
jQuery.fn.exists = function(){return this.length>0;}
/* Page Load functions*/
function SetAutoExpand()
{
    $('.contact_textArea').autoResize({
    // On resize:
    onResize : function() {
        $(this).css({opacity:0.8});
    },
    // After resize:
    animateCallback : function() {
        $(this).css({opacity:1});
    },
    // Quite slow animation:
    animateDuration : 250,
    // More extra space:
    extraSpace : 0
});
}
function ShowMain()
{
    $("#MainContentContainer").show();
    $("#MainContentLoader").hide();
    
   
}
function ShowMiddle()
{
     $("#loading_news").hide();
     $("#NewsTable").show();
}
function SetUpSelectMenues()
{
    //Dropdowns
    try{
        $('.dropdown').selectmenu({style:'dropdown',maxHeight:150});
    }
    catch(ex){}
    $('#modtager').selectmenu({style:'dropdown',maxHeight:150});
    //$('select#ContactSubject').selectmenu();
   // $('select#ContactSubject').selectmenu({maxHeight: 150});
    $('.fav_team').selectmenu({style:'dropdown',maxHeight:150,
		icons: [
			{find: '.soccer'},
            {find: '.hockey'},
            {find: '.football'}
		]
	});
    $('.news_dropdown').selectmenu({style:'dropdown',maxHeight:150,
		icons: [
			{find: '.soccer'},
            {find: '.hockey'},
            {find: '.football'},
            {find: '.all'}
		]
	});
}
function ShowRightSide()
{
    //Vis supportere
    $("#rightSupporters").show();
    $("#rightSupportersLandshold").show();
}
function SetUpNewsBar()
{
    try{
        $('#inNews').show();
        $('#inNews').marquee('pointer').mouseover(function () {
            $(this).trigger('stop');
        }).mouseout(function () {
            $(this).trigger('start');
        }).mousemove(function (event) {
            if ($(this).data('drag') == true) {
                this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
            }
        }).mousedown(function (event) {
            $(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
        }).mouseup(function () {
            $(this).data('drag', false);
        });
    }
    catch(ex){} 
}
function PreloadAll()
{
    //Preloading af billeder som er hover
    $(".knap_png").each(function() {
       var image =  HentHoverPic($(this).attr("src"),true);
       $("#preloadedImages").append('<img src="'+image+'" />');
    });
    
    //Preloading af andre
    var preloaded_images=new Array(); 
    preloaded_images[0]="images/sprogmenu/bg_sprogmenu.png";
    preloaded_images[0]="/images/sprogmenu/bund_sprogmenu.png";
    for(var i in preloaded_images)
    {
        $("#preloadedImages").append('<img src="'+preloaded_images[i]+'" />'); 
    }
}
function SetUpHoverImages()
{
     //Kode til mouseover på knapper    
	$(".knap").hover(function() {
	    var pic = $(this).css('backgroundImage').replace(/^url|[\(\)"']/g, '');
        var src = $(this).attr("src");
        $(this).css('backgroundImage','url('+src+')');
		$(this).attr("src",pic);
			}, function() {
		var pic = $(this).css('backgroundImage').replace(/^url|[\(\)"']/g, '');
        var src = $(this).attr("src");
        $(this).css('backgroundImage','url('+src+')');
		$(this).attr("src",pic);
	});
    $(".knap_png").hover(function() { 
            $(this).attr("src",HentHoverPic($(this).attr("src"),true));
			}, function() {
             $(this).attr("src",HentHoverPic($(this).attr("src"),false));
	});
    $("#FavoriteTeamIcon").hover(function(){
        $("#FavoriteTeamButton").attr("src","images/usermenu/favorite/button_2.png");
    });
    $(".menu_button").hover(function() { 
            $(this).attr("src",HentHoverPic($(this).attr("src"),true));
			}, function() {
             $(this).attr("src",HentHoverPic($(this).attr("src"),false));
	});
   /* $(".menu_button").click(function() 
        { 
            $(this).hover(function() { 
                $(this).attr("src",HentHoverPic($(this).attr("src"),true));
			}, function() {
                 $(this).attr("src",HentHoverPic($(this).attr("src"),true));
	        });
            $(this).attr("src",HentHoverPic($(this).attr("src"),true));
	   }
    );*/
}
function SetAutoComplete()
{
     var a = $('#query').autocomplete({ 
        serviceUrl:'ajax/autocomplete.php',
        minChars:1, 
        maxHeight:397,
        width:216,
        zIndex: 9999,
        noCache: false, //default is false, set to true to disable caching
        // callback function:
        onSelect: function(value, data){ var room_id = data.split("|")[1]; if(room_id != ""){ window.location='/'+room_id;} else { $('#query').val(""); } }
    });
    if(page == "index")
    {
        var b = $('#favorite_team').autocomplete({ 
            serviceUrl:'ajax/autocomplete.php',
            minChars:1, 
            maxHeight:397,
            width:216,
            zIndex: 9999,
            noCache: false, //default is false, set to true to disable caching
            uid: 'index',
            // callback function:
            onSelect: function(value, data){ var room_id = data.split("|")[1]; if(room_id != ""){ $("#favorite_team_hidden").val(room_id)} else { $('#favorite_team_hidden').val(""); } }
        });
    }
}
/* Page Load functions end */
/* TimeZone fix*/

var tzo=(new Date().getTimezoneOffset()/60)*(-1);
if(readCookie('sporturntzo') == null)
	createCookie('sporturntzo',tzo,14);	
/* TimeZone Fix end */
/*Functions*/
    function HentHoverPic(filnavn,er_over)
    {
        
        var ext = HentExtension(filnavn);
        var src = "";
        if(er_over)
        {
            if(filnavn.indexOf("_2."+ext) == -1)
                src = filnavn.replace("."+ext,"_2."+ext);
            else
                src = filnavn;
        }
        else
        {
            if(filnavn.indexOf("_2."+ext) > -1)
                src = filnavn.replace("_2."+ext,"."+ext);
            else
                src = filnavn;
        } 
         
        return src;
        
    }
    function HentExtension(filnavn)
    {
        return filnavn.split('.').pop();
    }
    function createCookie(name,value,days) {
    	if (days) {
    		var date = new Date();
    		date.setTime(date.getTime()+(days*24*60*60*1000));
    		var expires = "; expires="+date.toGMTString();
    	}
    	else var expires = "";
    	document.cookie = name+"="+value+expires+"; path=/";
    }
    function readCookie(name) {
    	var nameEQ = name + "=";
    	var ca = document.cookie.split(';');
    	for(var i=0;i < ca.length;i++) {
    		var c = ca[i];
    		while (c.charAt(0)==' ') c = c.substring(1,c.length);
    		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    	}
    	return null;
    }

	function CheckForSubmit(e)
	{
		if(e.type == "keypress")
		{
			if(e.keyCode == "13")
			{
				Login();
				return false;
			}
		}
	}
	function goto(url) {
		location.href = url;
	}
	function MakeVisible() 
	{
		overAlt = document.getElementById("OverAlt");
		overAlt.style.opacity=1;	
	}
	function Login()
	{
		document.loginform.submit();
	}
    function ToggleMenu(id,button)
    {
        if(erMenuAaben(id)){
            LukMenu(id);
           $(button).hover(function() { 
                $(this).attr("src",HentHoverPic($(this).attr("src"),true));
			}, function() {
                 $(this).attr("src",HentHoverPic($(this).attr("src"),false));
	        });
        }
            
        else{
            
            AabenMenu(id);
            $(button).hover(function() { 
                $(this).attr("src",HentHoverPic($(this).attr("src"),true));
			}, function() {
                 $(this).attr("src",HentHoverPic($(this).attr("src"),true));
	        });
        }
            
    }
    function erMenuAaben(id)
    {
        if($('#'+id+'').css('visibility') == "hidden")
            return false;
        else
            return true;
    }
    function LukMenu(id)
    {
        $('#'+id+'').css('visibility','hidden');
        $('#'+id+'').css('display','none');
    }
    function AabenMenu(id)
    {
        LukAlleMenuer();
        $('#'+id+'').css('visibility','visible');
        $('#'+id+'').css('display','block');
        
    }
    function LukAlleMenuer()
    {
        var menuer=new Array(); 
        menuer[0]="SprogMenuContainer";
        menuer[1]="ProfilMenuContainer";
        menuer[2]="NotifikationContainer";
        menuer[3]="AabenContainer";
        menuer[4]="IndbakkeContainer";
        menuer[5]="AnmodningContainer";
        menuer[6]="LikeMenuContainer";
        for(var i in menuer)
        {
            if(erMenuAaben(menuer[i]))
                LukMenu(menuer[i]);
        }
         $(".menu_button").hover(function() { 
            $(this).attr("src",HentHoverPic($(this).attr("src"),true));
		}, function() {
             $(this).attr("src",HentHoverPic($(this).attr("src"),false));
        });
        
    }
    function markInboxAsRead()
    {
        $.get("ajax/markInboxAsRead.php", function(data) 
		{
		  
			if(data == "1")
            {
                var src = "images/topikoner/indbakke/knap_indbakke.png";
                if($("#knap_indbakke").attr("src") != src)
                    $("#knap_indbakke").attr("src",src);
            }
            else
            {
                //no success
            }
		} );
    }
    function getRoomId()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        if(vars['room_id'] == null)
            return 0;
        else
            return vars['room_id'];
    }
    /* Friends */
	function AcceptFriend(app,acc)
	{
		$.get("ajax/AcceptFriend.php", { applier:app,accepter:acc }, function(data) 
		{
			var divid = '#Anmodning_'+app+'_'+acc;
			$(divid).slideUp(function() {
			     
		          if(CheckRequests() == -1)
                  {
                    $("#anmodningIkon").attr("src","images/topikoner/anmodning/knap_anmodning.png");
                    LukAlleMenuer();
                  }	 
			});
		} );
        
	}
    function CheckRequests()
    {
        return $("#AnmodningBg > div:visible").length-1;
    }
 	function DenyFriend(app,acc)
	{
		$.get("ajax/DenyFriend.php", { applier:app,accepter:acc }, function(data) 
		{
			var divid = '#Anmodning_'+app+'_'+acc;
			$(divid).slideUp(function() {
			   if(CheckRequests() == -1)
                  {
                    $("#anmodningIkon").attr("src","images/topikoner/anmodning/knap_anmodning.png");
                    LukAlleMenuer()
                  }	 
			 }
            );
		} );
	}
    /* Friends end */
    /* Like / Favorite */
	function ToggleFavorite(r)
	{
        $.get("ajax/marker_support_favorite.php", { favorite:1, room_id:r },function(data) { 
            if(data == 1)
            {
                $("#Favorit").attr("src","/images/right/favorit2.png");
                $("#Favorit").attr("onclick","");
                $("#UserFavoriteTeam").attr("src","/images/subbanner/"+r+".png");
                $("#FavoriteTeamLink").attr("href","/chat.php?room_id="+r);
                $("#FavoriteTeamIcon").attr("src","/images/ligaikoner/"+r+".png");
            }
            else
                $("#Favorit").attr("src","/images/right/favorit.png");
        });
        
	}
	function RemoveFromFavorite(room_id)
	{
		ajaxManager('send', 'ajax/marker_support_favorite.php?favorite=remove&room_id='+room_id);
	}
	function AddSupport(rid)
	{
	   if($("#isLike").val() == 0)
       {
            $.get("ajax/marker_support_favorite.php",{support:'add',room_id:rid});
            $("#Like").attr("src","/images/right/like2.png");
            $("#isLike").val("1"); 
            if($("#isDislike").val() == 1)
                RemoveDislike(rid);
	   }
       else
       {
            RemoveSupport(room_id);
       }
	   
	}
	function RemoveSupport(rid)
	{
	   if($("#isLike").val() == 1)
       {
    	   $.get("ajax/marker_support_favorite.php",{support:'remove',room_id:rid});
           $("#Like").attr("src","/images/right/like.png");
           $("#isLike").val("0"); 
       }
       else
       {
            AddSupport(rid);
       }
	}
    function AddDislike(rid)
	{
	    if($("#isDislike").val() == 0)
       {
        
        $.get("ajax/marker_support_favorite.php",{dislike:'add',room_id:rid});
        $("#Dislike").attr("src","/images/right/dislike2.png");
        $("#isDislike").val("1"); 
        if($("#isLike").val() == 1)
                RemoveSupport(rid);
        }
        else
        {
            RemoveDislike(rid);
        }
        
	}
	function RemoveDislike(rid)
	{
	     if($("#isDislike").val() == 1)
       {
        $.get("ajax/marker_support_favorite.php",{dislike:'remove',room_id:rid});
        $("#Dislike").attr("src","/images/right/dislike.png");
        $("#isDislike").val("0"); 
        }
        else
        {
            AddDislike(rid);
        }
	}
    function DisplayLikeError(message)
    {
        $("#LikeError").html(message);
    }
    function DisplayLeftError(message)
    {
        $("#LeftError").show();
        $("#LeftError").html(message);
    }
    /* Like / Favorite end */
    /*News functions*/
    function LikeNews(id)
    {
        var isLike = "#LikeNews_"+id;
        var isDisLike = "#DislikeNews_"+id;
        var imgField = "#LikeNewsImg_"+id;  
        var counter = "#LikesCount_"+id;
        var counterValue = $(counter).html() * 1;
         
           if($(isLike).val() == 0)
           {
                $.get("ajax/like_dislike_news.php",{like:'add',nid:id});
                $(imgField).attr("src","/images/news/like2.png");
                $(isLike).val("1"); 
                
                $(counter).html(counterValue+1);
                if($(isDisLike).val() == 1)
                    DislikeNews(id,'remove');
            }
            else
            {
                $.get("ajax/like_dislike_news.php",{like:'remove',nid:id});
                $(imgField).attr("src","/images/news/like.png");
                $(isLike).val("0"); 
                $(counter).html(counterValue-1);
            } 
        counterValue = $(counter).html() * 1;
        if(counterValue > 0)
            $(counter).attr("class","greenText");
        else
            $(counter).attr("class","greyText");
        
    }
    function DislikeNews(id)
    {
        var isLike = "#LikeNews_"+id;
        var isDisLike = "#DislikeNews_"+id;
        var imgField = "#DislikeNewsImg_"+id;  
        var counter = "#DislikesCount_"+id;
       var counterValue = $(counter).html() * 1;
       
           if($(isDisLike).val() == 0)
           {
                $.get("ajax/like_dislike_news.php",{dislike:'add',nid:id});
                $(imgField).attr("src","/images/news/dislike2.png");
                $(isDisLike).val("1"); 
                
                $(counter).html(counterValue+1);
                if($(isLike).val() == 1)
                    LikeNews(id);
            }
            else
            {
                $.get("ajax/like_dislike_news.php",{dislike:'remove',nid:id});
                $(imgField).attr("src","/images/news/dislike.png");
                $(isDisLike).val("0"); 
                $(counter).html(counterValue-1);
                
            } 
            counterValue = $(counter).html() * 1;
            if(counterValue > 0)
                $(counter).attr("class","error");
            else
                $(counter).attr("class","greyText");
        
    }
    function ToggleComments(id)
    {
        var row = "#NewsCommentsContainer_"+id;
        var isVisible = false;
        if($(row).is(":visible"))
        {
            isVisible = true;
        }
        //Close all first
        $("[id^=NewsCommentsContainer]").hide();
        
        if(isVisible)
        {
            $(row).hide();
        }
        else
        {
            $(row).show();
        }
        
        GetNewsComments(id);
    }
    function GetNewsComments(id)
    {
        var container = "#NewsComments_"+id;
        $.get("ajax/getNewsComments.php",{news_id:id},function(data) {
            $(container).html(data);
        });
    }
    /* News functions end */
    /*Reply funtions*/
    function ToggleReplies(id)
    {
        var row = "#PrivateMessageReplyContainer_"+id;
        var isVisible = false;
        if($(row).is(":visible"))
        {
            isVisible = true;
        }
        //Close all first
        $("[id^=PrivateMessageReplyContainer]").hide();
        
        if(isVisible)
        {
            $(row).hide();
        }
        else
        {
            $(row).show();
        }
        
        GetReplies(id);
    }
    function GetReplies(pm_id)
    {
        var container = "#PrivateMessageReplies_"+pm_id;
        $.get("ajax/getPrivateMessageReplies.php",{id:pm_id},function(data) {
            $(container).html(data);
        });
    }
    /*Reply functions end*/
	function SkiftBrugerPic(room_id)
	{
	  	
        
		if(room_id != "")
	        $("#profileCreateTeamPic").html('<img src="images/subbanner/'+room_id+'.png" />');
        else
             $("#profileCreateTeamPic").html('');	
		
	}
    function SendContactMessage()
    {
        var e = $("#ContactEmail").val();
        var s = $("#ContactSubject").val();
        var m = $("#ContactMessage").val();
        
        $.get("ajax/sendContact.php",{email:e, subject:s, message:m},function(data)
        {
            if(data == "1")
            {
                $("#ContactSuccessMessage").show();
                $("#ContactErrorMessage").hide();
            }
            else
            {
                $("#ContactSuccessMessage").hide();
                $("#ContactErrorMessage").show();
            }
        });
    }
    function pwdFocus(id) {
        $('#fakepassword'+id).hide();
        $('#password'+id).show();
        $('#password'+id).focus();
    }

    function pwdBlur(id) {
        if ($('#password'+id).attr('value') == '') {
            $('#password'+id).hide();
            $('#fakepassword'+id).show();
        }
    }
    function SetUpModalPopupViewProfile()
    {
        SetModal('.profileView');
        
         //if close button is clicked
        $('.window .close').click(function (e) {
            //Cancel the link behavior
            e.preventDefault();
            $('#mask, .window').hide();
        });     
         
        //if mask is clicked
        $('#mask').click(function () {
            $(this).hide();
            $('.window').hide();
        });        
    }
    function SetUpModalPopup()
    {
        SetModal('#ForgotPasswordLink');
        SetModal('#ForgotPasswordLinkFrontPage');
        SetModal('#ContactLink');
        SetModal('#ProfileEditFriendsLink');
        SetModal('#ProfileEditLink');
        SetModal('#ProfileDeleteLink');
        SetModal('.profileView');
        SetModal('.loginErrorLink');
        
        //if close button is clicked
        $('.window .close').click(function (e) {
            //Cancel the link behavior
            e.preventDefault();
            $('#mask, .window').hide();
             $("#PE_success").hide();
            $("#PE_error").hide();
        });     
         
        //if mask is clicked
        $('#mask').click(function () {
            $(this).hide();
            $('.window').hide();
            $("#PE_success").hide();
            $("#PE_error").hide();
        });         
    }
    function SetModal(id)
    {
        var tmp_id = id;
        $(id).unbind('click');
         $(id).click(function(e) {
            //Cancel the link behavior
            e.preventDefault();
            
            //Close existing modals
            $(".close").click();
            
            if($(this).attr("userId") != null)
            {
                
                var userId = $(this).attr('userId');
                if(!GetProfileView(userId))
                    return;
            }
            
            //Get the A tag
            var id = $(this).attr('href');
         
            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();
         
            //Set height and width to mask to fill up the whole screen
            $('#mask').css({'width':maskWidth,'height':maskHeight});
             
            //transition effect     
           // $('#mask').fadeIn(100);    
            $('#mask').fadeTo("fast",0.50);  
         
            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();
            
            var pxFromTop;
            if(tmp_id == ".loginErrorLink")
            {
            
                pxFromTop = 250;
            }
            else
            {
                pxFromTop = 100;    
            }
            
            
            //Set the popup window to center
            $(id).css('top',  pxFromTop);
            $(id).css('left', winW/2-$(id).width()/2);
         
            //transition effect
            $(id).fadeIn(100); 
            
        });
    }
    /*Online Teams*/
    function DisplayOnlineTeam(team)
   {
        
        var cssClass = "";
        if(team.antal == 0)
        {
            cssClass = "error";
        }
        else
        {
            $("#FrontPageOnlineTeamUsersContainer_"+team.nameKey).removeClass("error");
        }
        var template = '<div class="frontPageOnlineTeam" id="FrontPageOnlineTeam_'+team.nameKey+'" onclick="window.location=\'/'+team.nameKey+'\'"><div class="frontPageOnlineTeamIcon"><img src="images/ligaikoner/'+team.room_id
            +'.png" /></div><div class="frontPageOnlineTeamName"><a href="/'+team.nameKey+'" title="'+team.text+'" alt="'+team.text+'">'+team.text+'</a><div id="FrontPageOnlineTeamUsersContainer_'+team.nameKey+'" class="frontPageOnlineTeamUsersContainer '+cssClass+'"><span class="frontPageOnlineTeamUsers numberOfOnlineUsers" id="FrontPageOnlineTeamUsers_'+team.nameKey+'">'+team.antal
            +'</span> <span class="frontPageOnlineTeamUsers">online</span><div></div></div>';
        var updateTemplate = '<div class="frontPageOnlineTeamIcon"><img src="images/ligaikoner/'+team.room_id
            +'.png" /></div><div class="frontPageOnlineTeamName"><a href="/'+team.nameKey+'" title="'+team.text+'" alt="'+team.text+'">'+team.text+'</a><div id="FrontPageOnlineTeamUsersContainer_'+team.nameKey+'" class="frontPageOnlineTeamUsersContainer '+cssClass+'"><span class="frontPageOnlineTeamUsers" id="FrontPageOnlineTeamUsers_'+team.nameKey+'">'+team.antal
            +'</span> <span class="frontPageOnlineTeamUsers">online</span></div></div>';
        if($("#FrontPageOnlineTeam_"+team.nameKey).length == 0)
        {
            $("#FrontPageOnlineTeamsContainer").append(template);    
        }
        else
        {
            if($("#FrontPageOnlineTeamUsers_"+team.nameKey).text()*1 != team.antal)
            {
                $("#FrontPageOnlineTeam_"+team.nameKey).empty().append(updateTemplate);   
            }
            else
            {
            } 
        }
   }
   function ChangeOnlineTeamStyling()
   {
        var counter = 1;
        $(".frontPageOnlineTeam").each(function()
        {
            if(counter % 2 == 0)
            {
                $(this).css("background-color","#fff");
                $(this).hover(function(){$(this).css("background-color","#bfefc3");},function(){$(this).css("background-color","#fff");})
            }
            else
            {
                $(this).css("background-color","#e6eff4");
                $(this).hover(function(){$(this).css("background-color","#bfefc3");},function(){$(this).css("background-color","#e6eff4");})
            }

            counter++;
        });
   }
   function LoadOnlineTeams(){
       $.ajax({
          url: 'ajax/getOnlineTeams.php', 
          cache: false,
          dataType: 'json',
          success: function(data){
            var teams = "";
            for(var i=0;i<data.teams.length;i++)
            {
                if(data.teams[i] != null)
                {
                    DisplayOnlineTeam(data.teams[i]);
                    teams += data.teams[i].nameKey+","; 
                }			 	
            }
            RemoveOfflineTeams(teams);
          }
        });
        setTimeout('LoadOnlineTeams()', 10000);
    }
    function GetOnlineTeamsForBrowse()
    {
          $.ajax({
          url: 'ajax/getOnlineTeams.php', 
          cache: false,
          dataType: 'json',
          success: function(data){
            var teams = "";
            $(".numberOfOnlineUsers").html("0");
            $(".frontPageOnlineTeamUsersContainer").addClass("error");
            
            for(var i=0;i<data.teams.length;i++)
            {
                if(data.teams[i] != null)
                {
                    $('#FrontPageOnlineTeamUsers_'+data.teams[i].nameKey).html(data.teams[i].antal);
                    DisplayOnlineTeam(data.teams[i]); 
                }			 	
            }
          }
        });
        setTimeout('GetOnlineTeamsForBrowse()', 10000);
    }
    function LoadAllTeams(){
       $.ajax({
          url: 'ajax/getAllTeams.php', 
          cache: false,
          dataType: 'json',
          success: function(data){
            for(var i=0;i<data.teams.length;i++)
            {
                if(data.teams[i] != null)
                {
                    DisplayOnlineTeam(data.teams[i]); 
                }			 	
            }
            ChangeOnlineTeamStyling();
            GetOnlineTeamsForBrowse();
            $("#BrowseLoader").hide();
          }
        });
    }
    function RemoveOfflineTeams(teams)
    {
       $(".frontPageOnlineTeam").each(function()
        {
            var nameKey = $(this).attr("id").replace("FrontPageOnlineTeam_","");
            if(teams.indexOf(nameKey) == -1)
            {
                $(this).remove();
            }
        });
        ChangeOnlineTeamStyling();
    }
    /*Online Teams end*/
    /*Ajax functions*/
    function ResetPassword()
    {
        var forgottenPasswordEmail = $("#forgottenPasswordEmail").val();
        if(forgottenPasswordEmail != "")
        {
             $.get("ajax/resetPassword.php", {email:forgottenPasswordEmail},function(data)
             {
                $("#ResetPasswordMessage").html(data);
                $("#forgottenPasswordEmail").val("");
             });
        }
        else
        {
            
        }
    }
    function GetProfileView(userId)
    {
        if(userId > 0)
        {
            
            if($("#ProfileViewID").val() != userId )
            {
           // console.log($("#ProfileViewID").val() +" - "+ userId)
                $.get('ajax/profileView.php',{id:userId},function(data){
                   $("#ProfileViewDialog").html(data);
                   $("#ProfileViewID").val(userId);
                   SetUpModalPopupViewProfile();
                   SetUpHoverImages();
                });
                return true;
            }
            else
            {
                return true;    
            }
        }
        else
        {
            $("#ProfileViewDialog").html('');
        }
        return false;
    }
    function SaveProfile()
    {
        $("#EditProfileLoader").show();
        var PE_brug_billede,PE_email,PE_pass1,PE_pass2,PE_hold,PE_sex,PE_birthday_yy,PE_birth_city,PE_current_city,PE_land;
        PE_brug_billede = $("#PE_brug_billede").val();
        PE_email = $("#PE_email").val();
        PE_pass1 = $("#PE_pass1").val();
        PE_pass2 = $("#PE_pass2").val();
        PE_hold = $("#PE_hold").val();
        PE_sex = $("#PE_sex").val();
        PE_birthday_yy = $("#PE_birthday_yy").val();
        PE_birth_city = $("#PE_birth_city").val();
        PE_current_city = $("#PE_current_city").val();
        PE_land = $("#PE_land").val();
        
        
        $.getJSON("ajax/profileEdit.php",{brug_billede:PE_brug_billede,email:PE_email,pass1:PE_pass1,pass2:PE_pass2,hold:PE_hold,sex:PE_sex,birthday_yy:PE_birthday_yy
        ,birth_city:PE_birth_city,current_city:PE_current_city,land:PE_land},function(data)
        {
           if(data.success)
           {
                $("#PE_success").show();
                $("#PE_error").hide();
           }
           else
           {
                $("#PE_error").html(data.error);
                $("#PE_error").show();
                $("#PE_success").hide();
           }
           $("#EditProfileLoader").hide();
        });
    }
    function DeleteProfile()
    {
        $.get('ajax/profileDelete.php',function(data){
           if(data == "1")
           {
                window.location = "/";
           }
           else
           {
            
           }
        });
    }
    /*Ajax functions end*/
    function AppendSmiley(s)
    {
        $('#chatTextInput').val($('#chatTextInput').val()+s);
        $('#chatTextInput').focus();
    }
    function replaceAll(txt, replace, with_this) {
        return txt.replace(new RegExp(replace, 'g'),with_this);
    }
    /*profile.js*/
    var okImg = "<img src='../images/index/ok.png' style='margin-bottom: 0px;margin-left: 0px;'>";
var ok2Img = "<img src='../images/index/ok2.png' style='margin-bottom: 0px;margin-left: 0px;'>";
var nixImg = "<img src='../images/index/nix.png' style='margin-bottom: 0px;margin-left: 0px;'>";
 $(window).bind('load', function () {
 var a = $('#fav_team_query').autocomplete({ 
        serviceUrl:'ajax/autocomplete.php',
        minChars:1, 
        maxHeight:400,
        width:222,
        zIndex: 9999,
        noCache: false, //default is false, set to true to disable caching
        uid: 'profile',
        // callback function:
        onSelect: function(value, data){
            var room_id = data.split("|")[0]; 
            if(room_id > 0){
                $("#PE_hold").val(room_id);
                SkiftBrugerPic(room_id);     
            } 
        }
    });
});
function CheckNick()
{
    var nickName = $("#username").val();
    if(nickName.length == 0)
    {
        SkiftStjerneTilFlueBen("nickStjerne",false);
        return;
    }
             
    $.get("ajax/isNickAvailable.php", {nick:nickName}, function(data) {
       if(data == "1")
       {
            SkiftStjerneTilFlueBen("nickStjerne",true);
       }
       else
       {
            SkiftStjerneTilFlueBen("nickStjerne",false);
       }
    });
}
function SkiftStjerneTilFlueBen(id,er_on){
    
    var elem = document.getElementById(id)
    if(er_on == 3)
    {
            elem.innerHTML = ok2Img;
            elem.style.background = "none";
    }
    else if(er_on){
        elem.innerHTML = okImg;
        elem.style.background = "none";
    }
    else
    {
        elem.innerHTML = nixImg;
        elem.style.background = "none";
    }

}
function CheckEmail()
{
	emailadress = $("#PE_email").val();
   
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	if(!emailadress.match(re))
    {
        SkiftStjerneTilFlueBen("emailStjerne",false);
        return;
    }
    
        //Check if exists    
         $.get("ajax/isEmailAvailable.php", {email:emailadress}, function(data) {
           if(data == "1")
           {
                SkiftStjerneTilFlueBen("emailStjerne",true);
           }
           else
           {
                SkiftStjerneTilFlueBen("emailStjerne",false);
           } 
        });
}

function CheckPass()
{
	pass = document.getElementById("PE_pass1");
	password = pass.value;
	if(password.length == 0)
            SkiftStjerneTilFlueBen("pass1Stjerne",false);
	else if(password.length<=6)
		SkiftStjerneTilFlueBen("pass1Stjerne",3);
	else if(password.length > 6)
		SkiftStjerneTilFlueBen("pass1Stjerne",true);
}
function ClearPass2()
{
        pass2 = document.getElementById("PE_pass2").value = "";
        SkiftStjerneTilFlueBen("pass2Stjerne",false);
}
function CheckPass2()
{
	pass2 = document.getElementById("PE_pass2");	
	password = pass2.value;
	if(password != document.getElementById("PE_pass1").value)
	{
            SkiftStjerneTilFlueBen("pass2Stjerne",false);
            return false;
	}
	else
	{
            SkiftStjerneTilFlueBen("pass2Stjerne",true);
            return true;
	}
}
function RemoveFriendAsk(friendId,trid,confirmID,deleteLinkID)
{
    $("#"+confirmID).show();
    $("#"+deleteLinkID).hide();
}
function RemoveFriend(friendId,trid)
{
    $.get("ajax/removeFriend.php",{id:friendId},function(data) {
            if(data == "1")
            {
                $(".friend_"+trid).fadeOut();
            }
        });   
}
function ProfileViewRemoveFriend(friendId)
{
    $.get("ajax/removeFriend.php",{id:friendId},function(data) {
            if(data == "1")
            {
                $("#RemoveFriendLink").hide();
                $("#AddFriendLink").show();
            }
        });
        
}
function ProfileViewAddFriend(friendId)
{
    $.get("ajax/addFriend.php",{id:friendId},function(data) {
            if(data == "1")
            {
                $("#AddFriendLink").hide();
                $("#friend_added").show();
            }
        });
        
}
    /*profile.js end*/
