var content=new Array();
content['footer'] = '<div class=\"feedEntry\"><div class=\"feed-13\" title=\"Gruppe gegründet\"></div><div class=\"feedEntryText\"><div class=\"feedEntryTime\">18:20 Uhr</div><div class=\"feedEntryDescription\"><a href=\"http://seo.joinr.de\">seo</a> hat die Gruppe <a href=\"/groups/pipe/10704/\">aaaaa</a> in  gegründet</div></div><div class=\"clear\"></div></div>';
content['misc/screensaver'] = '<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"100%\" height=\"100%\" id=\"starfield\" align=\"middle\"><param name=\"movie\" value=\"/starfield.swf\" /><param name=\"quality\" value=\"high\" /><param name=\"bgcolor\" value=\"#e8edd6\" /><embed src=\"/starfield.swf\" quality=\"high\" bgcolor=\"#e8edd6\" width=\"100%\" height=\"100%\" name=\"starfield\" align=\"middle\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" /></object>';
content['lightbox/login'] = '<div class=\"lightbox-login\"><form action=\"/login/\" method=\"post\"><span class=\"login\">Login</span><label for=\"name\">Benutzername</label><input type=\"text\" name=\"username\" class=\"lightbox-login-input\" id=\"name\" /><label for=\"pass\">Passwort</label><input type=\"password\" class=\"lightbox-login-input\" name=\"password\" id=\"pass\" /><br /><input type=\"submit\" class=\"button orange-default button-ffffff\" value=\"Login\" /></form></div>';
content['lightbox/tryAgain'] = '<div class=\"lightbox-error\"><span class=\"error-headline\">Hoppla</span><p>Hier ist wohl ein Fehler aufgetreten</p><input type=\"submit\" class=\"button orange-default button-ffffff\" value=\"Nochmal\" /><input type=\"submit\" class=\"button iceBorder-default button-ffffff\" value=\"Abbrechen\" /></div>';
content['lightbox/continuesError'] = '<div class=\"lightbox-error\"><span class=\"error-headline\">Hoppla</span<p>Hier ist wohl der gleiche Fehler nochmal aufgetreten</p><b>Fehlerbeschreibung:</b><br><textarea name=\"error\" style=\"width:100%;height:50px; margin-bottom:5px;\"></textarea><input type=\"submit\" class=\"button iceBorder-default button-ffffff\" style=\"float:right\" value=\"Abbrechen\" /><input type=\"submit\" class=\"button orange-default button-ffffff\" value=\"Senden\" /></div>';
var showMsg=0;
$$(function()
{
    if(!window.console)
    {
        window.console=
        {
           'log':function(){}
        };
    }
    setTimeout(checkDo,10000);
}); 

        //notify
        function checkForNotifies()
        {
            $$.getJSON('/ajax.php', { f: "messages/update", msg:numMsgs },function(data, textStatus)
            {
                if(isset(data.msg))
                {
                    if(data.msg>showMsg)
                    {
                        favicon.animate(new Array("/static/icon/msg01.png", "/static/icon/msg02.png", "/static/icon/msg03.png"));
                        if(document.title!='Neue Nachricht')
                        {
                            lastTitle=document.title;
                            document.title='Neue Nachricht';
                        }
                        currentIcon='newMsg';
                        $$(".new_messages").html(data.msg);
                        //numMsgs=data.msg;
                        showMsg=data.msg;
                        $$("span.new-messages").show().text(data.msg).parent().attr("href","/messages/unread/");  
                    }
                    else
                    {
                         if(data.msg<showMsg)
                         {
                               favicon.change('/favicon.ico',lastTitle);
                               currentIcon='default';                                        
                             if(data.msg==0)
                             {
                                $$("span.new-messages").hide().text(data.msg).parent().attr("href","/messages/");    
                             }
                             else
                             {
                                $$("span.new-messages").show().text(data.msg).parent().attr("href","/messages/unread/");                                  
                             }
                             
                         }
                        
                    }
                }
                else
                {
                        if(currentIcon=='newMsg')
                        {
                           favicon.change('/favicon.ico',lastTitle);
                           currentIcon='default';                         
                            
                        }                      
                    
                }
            });
            setTimeout(checkForNotifies,60000);
        }
        
        
$$(function(){





    if(log)
    {
        showMsg=numMsgs;

        $$("#reportBugs").hide();
        $$("#reportButton").click(function()
        {
             $$("#reportBugs").slideToggle("slow");
        });
       

        setTimeout(checkForNotifies,30000);

       $$("#friends-online,div#friends-online-list-icon").click(function()
        {
             if($$("#change-mood").is(":visible"))
             {
               $$("#change-mood").hide();
               $$().unbind('mouseup', removeSelect);

             }
             if($$("#friends-online-list").is(":visible"))
             {
               $$("#friends-online-list").hide();
               $$().unbind('mouseup', removeSelect);

             }
             else
             {
                $$("#friends-online-list").show();
             }

        });

        $$("#friends-online-list,#friends-online").hover(function()
        {
           $$().unbind('mouseup', removeSelect);
        },
        function()
        {
            $$().mouseup(removeSelect);
        });

        $$("#friends-online-list select").change(function()
        {
             $$("#friends-online a span").html($$(this).children(":selected").text()).css({color:"#B1C33E"}).animate({color:"white"}, 2000);
             $$("#friends-online-list").hide();
             $$().unbind('mouseup', removeSelect);
            $$.getJSON('/ajax.php', { f: "misc/online", online:$$(this).val() },function(data, textStatus)
            {
                if(data.msg)
                {

                }
            });


        });

        
        
        
        
        
        


       $$("#change-mood-text,div#change-mood-icon").click(function()
        {
             if($$("#friends-online-list").is(":visible"))
             {
               $$("#friends-online-list").hide();
               $$().unbind('mouseup', removeSelect);

             }
             if($$("#change-mood").is(":visible"))
             {
               $$("#change-mood").hide();
               $$().unbind('mouseup', removeSelect);

             }
             else
             {
                $$("#change-mood").show();
             }

        });

        $$("#change-mood,#change-mood-text a").hover(function()
        {
           $$().unbind('mouseup', removeSelect);
        },
        function()
        {
            $$().mouseup(removeSelect);
        });

        $$("#change-mood-content select").change(function()
        {

             $$("#change-mood-text a span").html($$(this).children(":selected").text()).css({color:"#B1C33E"}).animate({color:"white"}, 2000);
             $$("#change-mood").hide();
             $$().unbind('mouseup', removeSelect);
            $$.getJSON('/ajax.php', { f: "misc/status", mood:$$(this).val() },function(data, textStatus)
            {
                if(data.msg)
                {

                }
            });

        });

    }

    //focus window
    $$().focus(function()
    {
        feed.setStatus(true);
        if(currentIcon!='default')
        {
            checkForNotifies();
            setTimeout(function()
            {
            favicon.change('/favicon.ico',lastTitle);
            currentIcon='default';
            },2000);
        }
    });


    //navi
    $$("ul#header-navi li.mainNav").hover(function()
    {
        if(menuTimeOut)
            menuTimeOut=clearTimeout(menuTimeOut);

            if(currentNavi && currentNavi!=this)
            {
                closeNavi(currentNavi);
                currentNavi=null;


            }
            currentNavi=this;
               $$(this).addClass("hover");
           $$(this).prev().children("a:first").css({borderRight:"1px solid #5d5d5d"});


        $$('ul:first',this).css('visibility', 'visible');

    },
    function()
    {
      if(menuTimeOut)
          menuTimeOut=clearTimeout(menuTimeOut);
    menuTimeOut=setTimeout(function(){ if(currentNavi) closeNavi(currentNavi);},500);

    });

    //search
    $$("#search-top-dropdown").click(function()
    {
        if($$("#search-top-dropdown-list").css("display")=="none")
          $$("#search-top-dropdown-list").css({display:"block"});
        else
          $$("#search-top-dropdown-list").css({display:"none"});
    })
    .hover(function(){},function()
    {
       $$("#search-top-dropdown-list").css({display:"none"});
    });


    $$("label").mousedown(function()
    {
        this.blur();
		$$("#"+$$(this).attr("for")).data("c",$$("#"+$$(this).attr("for")).attr("checked"));
    })

    $$("input[type='radio']").mousedown(function()
    {
		$$(this).data("c",this.checked);
    }).click(function()
    {
			  if(this.checked &&  $$(this).data("c"))
			     this.checked=false;
    });

});

var shiftPressed=false;

var conf=
{
    load:
    {
        small:"http://aa.joinrcdn.de/images/misc/loading/loading_small.gif",
        big:"http://aa.joinrcdn.de/images/misc/loading/loading_large.gif"   
    },
    static:"http://aa.jrimg.com/"
};
function parse_pic(str)
{
    if(str==null)
        return null;
        var pic=str.split(':');
     return {srv:rotate(pic[1]),path:pic[0].split(".")};
};
var time=(new Date()).getTime();
function rotate(srv)
{
    return srv.substr(time%(srv.length/2)*2,2);    
}
function isset(val)
{
 return typeof val!='undefined' && val!=null;   
}

function dpic(data, size, link, add) 
{
    var str='';
    if(!link) link=true;
    if(!size) size='';    
    if(!add) add='';   
     
    if(!(data['UName'])) {
		link = false;
	}

	if(log == true) {
		label = 'Homepage';
	} else {
		label = 'Kostenlose Homepage';
	}

	if(link) str+= '<a href="http://'+data['UUrl']+'/" title="'+label+' von '+data['UName']+'">';

	if(!(data['UPic']) || null === (p = parse_pic(data['UPic']))) 
	{
	   str+= '<img src="http://aa.jrimg.com/images/nopic/nopic-user-'+(size == '' ? 'normal' : size)+'.gif" alt="Kein Bild" '+add+'/>';
	} 
	else 
	{

		if(size == 'large') {
			size = 'm';
		} else if(size == 'small') {
			size = 'x';
		} else {
			size = 's';
		}
   
		str+= '<img src="http://'+p['srv']+'.jrimg.com/user/'+ p['path'][0]+'-'+size+'.jpg" alt="Profilbild von '+data['UName']+'" '+add+'/>';
	
	}

	if(link) str+= '</a>';
	
	return str;
}


function durl(data)
{
    return '<a href="http://'+data.UUrl+'">'+data.UName+'</a>';
}


conf.modifiers={durl:durl,dpic:dpic};






function $(id)
{
    return document.getElementById(id);
}
String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

function showScreenSaver()
{
 screenSaverActive=true;
var div=document.createElement("div");
div.id="saver";
document.body.appendChild(div);
div.style.position="fixed";
div.style.width="100%";
div.style.height="100%";
div.style.top="0px";
div.style.left="0px";

    div.innerHTML=content['misc/screensaver'];

}
function stopScreenSaver()
{
  screenSaverActive=false;
  $$("#saver").remove();
}


function reportBug()
{
    if(!$$("textarea[name='feedback']").val())
    {
     alert("Bitte beschreibe uns den Bug!");
     return false;   
    }
 $$.gepost("/ajax.php",{f:"misc/feedback"},function(){}, {text:$$("textarea[name='feedback']").val(),url:window.location.href});

 $$("#reportBugs").slideToggle("slow",function()
 {
     $$('<div class="successBugNote" style="width:100%; background:#B1C33E; padding-top:4px padding-bottom:4px;font-weight:bold; font-size:18px;color:white;" align="center">Deine Fehlerbericht wurde übermittelt!</div>').prependTo(document.body).hide().slideDown("slow");
setTimeout(function(){$$("div.successBugNote").slideUp("slow");},5000);

  });
 
}



var lastActivity=(new Date()).getTime();
var screenSaverActive=false;
 $$().bind("mousemove keypress", function(e)
 {
     feed.setStatus(true);
    lastActivity=(new Date()).getTime();
    if(screenSaverActive)
    {
       stopScreenSaver();
    }
 });

function checkDo()
{
    if(!screenSaverActive)
    {
    var now=(new Date()).getTime();
    if(now-lastActivity>1000*60*10)
    {
           feed.setStatus(false); //disable feed
        //showScreenSaver(); //disabled screenserver
    }
    }
setTimeout(checkDo,10000);
}




    document.onkeypress = function(e)
    {
         if (!e)
              e = window.event;

        if(!e.keyCode)
            return;
            
          switch (e.keyCode)
          {
             case 16://shift
             shiftPressed=true;
             break;
             case 112:
             //return false;
            break;
          }
    }
    document.onhelp = function()
    {
        if(log)
        {
            $$("#reportBugs").slideToggle("slow");
          return false;
        }
    }
    document.onkeydown = function(e)
    {
         if (!e)
              e = window.event;

        if(!e.keyCode)
            return;
        if(log)
        {
          switch (e.keyCode)
          {
             case 16://shift
             shiftPressed=false;
             break;
            case 112:
            $$("#reportBugs").slideToggle("slow");
            //return false;
            break;
          }

        }
    } //error login
    
 $$().ajaxError(function (event, XMLHttpRequest, ajaxOptions, thrownError) {
 
    $$("#header-navi li:first").hide();
     if(thrownError==500)
     {
        fail();
     }
 
  });
   function fail(settings)
   {
       if(settings.url!=tryAgain)
       {
            $$.getScript("/scripts/jquery.lightbox.js", function()
            {
              $$.lightbox.show(content['lightbox/tryAgain'],function()
              {
                  $$("div.lightbox-error input:last").click(function()
                  {
                    $$.lightbox.hide();   
                  });
                  $$("div.lightbox-error input:first").click(function()
                  {
                    tryAgain=settings.url;
                    $$.lightbox.hide();
                    setTimeout(function()
                    {     
                    $$.ajax(settings);         
                    },500);
                  });
                                    
                  
              });  
            });
       }
       else
       {
            $$.getScript("/scripts/jquery.lightbox.js", function()
            {
                    //todo: user .error(.. & tpl

              $$.lightbox.show(content['lightbox/continuesError'],function()
              {
                  $$("div.lightbox-error input:first").click(function()
                  {
                    $$.lightbox.hide();   
                  });
                  $$("div.lightbox-error input:last").click(function()
                  {
                    
                    $$.gepost("/ajax.php",{f:"misc/feedback"},function(){}, {text:$$("div.lightbox-error textarea[name='error']").val(),url:settings.url});

                    $$.lightbox.hide();                    
                  });
                                    
                  
              });  
            });
           
       }
   
   
   } 
 var tryAgain='';    
 var loginForm=false;
 $$().ajaxStart(function()
 {
      $$("#header-navi li:first").show();
 }
 );
 $$().ajaxComplete(
 function(event,request, settings)
 {
      $$("#header-navi li:first").hide();
   
   if(settings.url.indexOf("ajax.php")==-1)
    return;   
      
     if(log)
   switch(request.responseText)
   {
       case '0':
       if(loginForm)
           return;
       
       loginForm=true;
        $$.getScript("/scripts/jquery.lightbox.js", function()
        {
          $$.lightbox.show(content['lightbox/login']);
          
          checkLogStatus=setInterval(function()
          {
              $$.get('/ajax.php', { f: "misc/checkLogin"},function(data)
              {
                  if(data>0)
                  {
                    clearInterval(checkLogStatus); 
                    loginForm=false;
                    $$.lightbox.hide();
                  }
              });
          },1000);
        });
       
       break;
       case 'fail':
        fail(settings);
       break;
       default:
       tryAgain=''; 
       break;

   }
 });


//navigation
var currentNavi;
var menuTimeOut;
var searchCategory="user";
var currentIcon="default";
function closeNavi(navi)
{
      if($$((navi)).hasClass("mainNav"))
      {

        $$((navi)).prev().children("a:first").css({borderRight:"1px solid #cfcfcf"});
      }
        $$(navi).removeClass("hover");
        $$('ul:first',(navi)).css('visibility', 'hidden');
        menuTimeOut=null;
}



//global functions
function ignore(name,get)
{
  $$.get('/ajax.php',{f:'friends/addIgnore',user:name});

 if(get)
 {
  $$(get).parent().fadeOut("slow");

 }
}
var getKiss;
function kiss(name,get)
{

 $$.get('/ajax.php',{f:'messages/kiss',user:name});

 aniKiss(get);
}
var getKiss;
function aniKiss(get)
{
     getKiss=get;
  if($$("#kissImage"))
      $$('<img id="kissImage" onload="openAniKiss(getKiss)" style="width:0px; height:0px; position:fixed; top:0px; left:0px;" src="http://aa.joinrcdn.de/images/kussmund.gif">').appendTo(document.body);
  else
  {
      $$("#kissImage").show();
      
      openAniKiss(get);
  }
}
function openAniKiss(get)
{
 $$("#kissImage").css({opacity: 0.1});
 $$("#kissImage").animate({height: "350px", width: "400px",left:"100px", top:"100px",  opacity: 0.7}, 2500,null,function()
 {
   $$("#kissImage").animate({height: "0px", width: "0px",left:"0px", top:"0px",opacity: 0.1},"normal",null,function()
   {
     $$("#kissImage").hide();
   });

 });
 if(get)
 {
  $$(get).parent().fadeOut("slow");

 }     
}
function setInputsFromObject(inputs,ob)
{
    /*
    //input(text, radio) & select
    {name:value}
    */
        for (var index in ob)
        {
         var box=inputs.filter("[name='"+index+"']");

         if(box.is(":radio"))
         {
          box.filter("[value='"+ob[index]+"']:first").attr("checked",true);

         }
         else
          box.val(ob[index]);
        }

}


//header
function setSearchCat(val,get)
{
    searchCategory=val;
    $('search-top-dropdown-selected-text').innerHTML=get.innerHTML;
}
function search()
{
  var keywords=$('searchText').value;
  window.location="/search/#/"+searchCategory+"/"+(keywords?keywords+'/':'');
  if(typeof setTopSearch!='undefined')
  {

    searchPage(searchCategory);
    activeSearchPage=  searchCategory;
    setTopSearch(1);
  }
}
function truncate(str,len)
{
   if(str.length-3>len)
   {
     return str.substr(0,len-2)+'...';
   }
   return str;
}
function submitForm(get,id)
{
    if(id)
    {
        $(id).submit();
    }
    get.disabled=true;
}
function disableForm(get)
{
 $$("form :input[type='submit']").attr('disabled', true);
}
//todo: save title
var favicon =
{
    defaultPause: 800,
    change: function(iconURL, optionalDocTitle)
    {
      clearTimeout(this.loopTimer);
      if (optionalDocTitle)
      {
        document.title = optionalDocTitle;
      }
      this.addLink(iconURL, true);
    },

    animate: function(iconSequence, optionalDelay)
    {
      this.preloadIcons(iconSequence);
      this.iconSequence = iconSequence;
      this.sequencePause = (optionalDelay) ?  optionalDelay : this.defaultPause;
      favicon.index = 0;
      favicon.change(iconSequence[0]);
      this.loopTimer = setInterval(function()
      {
        favicon.index = (favicon.index+1) % favicon.iconSequence.length;
        favicon.addLink(favicon.iconSequence[favicon.index], false);
      }, favicon.sequencePause);
    },

    loopTimer: null,

    preloadIcons: function(iconSequence)
    {
      var dummyImageForPreloading = document.createElement("img");
      for (var i=0; i<iconSequence.length; i++)
      {
        dummyImageForPreloading.src = iconSequence[i];
      }
    },

    addLink: function(iconURL)
    {
      var link = document.createElement("link");
      link.type = "image/x-icon";
      link.rel = "shortcut icon";
      link.href = iconURL;
      this.removeLinkIfExists();
      this.docHead.appendChild(link);
    },

    removeLinkIfExists: function()
    {
      var links = this.docHead.getElementsByTagName("link");
      for (var i=0; i<links.length; i++)
      {
        var link = links[i];
        if (link.type=="image/x-icon" && link.rel=="shortcut icon")
        {
          this.docHead.removeChild(link);
          return; // Assuming only one match at most.
        }
      }
    },

    docHead:document.getElementsByTagName("head")[0]
}

//status & mood function
function removeSelect()
{
   $$("#change-mood").hide();
}
function saveStatus()
{
                 $$.getJSON('/ajax.php', { f: "misc/status", stat:$$("#change-status-text input").val() },function(data, textStatus)
                {
                    if(data.msg)
                    {

                    }
                });
                  $$("#change-status-text a").toggle().children("span").html(truncate($$("#change-status-text input").val(),20)).css({color:"#B1C33E"}).animate({color:"white"}, 2000);
                  $$("#change-status-text input").toggle();

}




//footer
var feed=function()
{
    var loadPos=0;
    var feedCon=new Array();
    var lastRequest=0;
    var minTimeBetween=20000;
    var running=false;
    var active=true;
    function next()
    {
        if(!active)
            return;
       if(feedCon.length==5)
        load();
       if(feedCon.length)
       { 
       var $child=$$($ob).prepend(feedCon[0]).children(":first").fadeIn("slow");
       
       var h=$child.innerHeight();
       $ob.css({top:"-"+h+"px",position:"relative" }).animate ({ top:"0px"}, 500);
       $child.fadeOut(0).fadeIn("slow");

  
  
         feedCon.splice(0,1);
        if($ob.children().length>5)
        {
            $ob.children(":last").remove();
        }
       
        setTimeout(function(){feed.displayNext()},750+Math.floor(Math.random() * 2500));
       }
       else
        running=false;
    };
    function load()
    {
        var currentTime=(new Date()).getTime();
        if(currentTime-lastRequest<minTimeBetween)
        {
            setTimeout(function()
            {
                feed.load();            
            },minTimeBetween-(currentTime-lastRequest));  
            
        }
        lastRequest=currentTime;
        
        
        $$.getJSON("/ajan.php",{f:"misc/footer","pos":loadPos},function(con)
        {
            if(con=="failure" || con=="0")
                return;
             currentPos=con.pos;
             insertContent(con.content);          
        });
        
    };
    function insertContent(con)
    {
        loadPos=currentPos+con.length;
        for(index in con)
        {
         feedCon.push(con[index]);   
        }
    };

    return {
        init:function(id,con)
        {
            currentPos=id;      
            running=true; 
            if(con) 
              insertContent(con);   
            $ob=$$("div.footer-whatsup-content div:first");
            next();
        },
        addContent:function(con)
        {           
            insertContent(con);   
        },
        displayNext:function()
        {
            next();   
        },
        setStatus:function(status)
        {
            active=status;
        },
        load:function()
        {
         load();   
        }
    };
    
}();


