

//jQuery Skripte
$(document).ready(function(){
    do_onload();

    $(".gc-quickbox_more").hover(
        function(){
            var menu = $(this).parent().children(".gc-quickbox_more_menu");
            menu.fadeIn("fast");
            var pos = menu.position();
            menu.css({
                top:pos.top+"px",
                left:pos.left+"px"
            });
           
        },
        function(){
            var menu = $(this).parent().children(".gc-quickbox_more_menu");
            menu.fadeOut("fast");
        }
        );

   
    fixPNGs();

    init_gui();
    init_live_handlers();
    init_tooltip();



    $("img").fullsize();
    par=$("img").parents("a[rel*=fullsize]");
    if(par!=null){
        par.click(function(){
            return false;
        })
        par.css("cursor","default");
    }

    if(adminmode)
    {
        $("div.module_header").each(function(){
            var name=$(this).attr("name");

            t=null;
            $(this).mouseover(function(){
                $("#"+name+"").show();$("#"+name+"").data("show",true);
            });
            $(this).mouseout(function(){
                $("#"+name+"").data("show",false);setTimeout(function(){
                    if(!$("#"+name+"").data("show")){
                        $("#"+name+"").stop(true,true);$("#"+name+"").hide()
                    }
                },1000)
            });
        });
    }

    //Deaktivieren, da ansonsten Probleme bei AJAX-Aufrufen
    document.write=function(text){};
});

function inline_handlers_to_jquery(selector,type){
    $(selector).each(function(){
        try{
            var handler=$(this).data("on"+type);
            if(handler == undefined || handler == null || handler == ""){
                handler=$(this).attr("on"+type);
                // Handler sichern (für Ajax reloads)
                $(this).data("on"+type,handler);
                $(this).attr("on"+type,"");
            }
             
            if(handler!=null){
                $(this).bind(type,eval(handler));
             
            }
        }catch(ex){}
    });
}

function init_live_handlers(){
/*$("form.inline input[type=submit]").live("click",function(event){
     
        var form=$(this).closest("form.inline");
        var href=form.attr("action");

        if(href==null||href==undefined||href=="")
            href=current_url;

        if(href.indexOf(global_domain)==0&&href.replace(global_domain, "").split("/").length>=4){

            var data=form.serialize();

            var currentData=data+(data!=""?"&":"")+this.name+"="+this.name;

            if(href.indexOf(base_url)!=-1) //Gleiche Seite
                ajaxUpdateModule(new Array("content"),href,currentData);
            else
                ajaxUpdateModule(new Array("content","menu/dynamic","user/head_userbox"),href,currentData);
             $(this).unbind("click");
            event.preventDefault();
        }
    });*/

  
}

function fixPNGs()
{

//BugFixPngs();
//$("img[src$=.png], .pngfix").ifixpng();
}

function content_edit(obj) {
    if(obj.css("display")=="none") {
        obj.show();
        $(".gc-edit_area").hide();
    }else{
        obj.hide();
        $(".gc-edit_area").show();
    }
   
}

var loadingHandlers = new Object();

function addLoadingHandler(name,callback){
    loadingHandlers[name]=callback;
    return true;
}

function init_gui() {
    init_messages();

    for(var handler in loadingHandlers){       
        (loadingHandlers[handler])();
    }
    $("a.inline").unbind("click");
    $("a.inline_action").unbind("click");
    $("a.inline_current").unbind("click");
    $("a.inline_outer").unbind("click");
    $("input[type='submit'].inline").unbind("click");

    //onclick-Handler umwandeln
    inline_handlers_to_jquery("a.inline_current","click");
    inline_handlers_to_jquery("a.inline_action","click");
    inline_handlers_to_jquery("a.inline_outer","click");
    inline_handlers_to_jquery("a.inline","click");

    $("input.gamebox").autocomplete(current_url,{
        extraParams:{
            show_single_module:escapeModule("ajax?action=autocomplete"),
            only_data:1
        },
        minChars:3,
        selectFirst:false,
        width:"180px"
    });

    $('.gc-head_userbox_container').css("width", $('.gc-head_userbox_info').width());
    $('.gc-head_userbox_container').css("height", $('.gc-head_userbox_info').height());
    $('.gc-head_userbox_changetoogle').click(function(){
        toogleChangebox();    
        return false;
    });



    $("input[type='submit'].inline").bind("click",function(event){
        var res=submitForm(this);
        if(res)
            event.preventDefault();
        return res;
    });



    $("a.inline_current").bind("click",function(event){
        if(event.result==false)
            return false;

        var module=$(this).closest(".gc-module").children("div[name=module-info]").text();
        var href=$(this).attr("href");

        if(href.indexOf(global_domain)!=-1&&href.replace(global_domain, "").split("/").length>=4) {
            ajaxUpdateSingleModule(module,href,"");
            event.preventDefault();
        }

        return true;
    });


    $("a.inline_outer").bind("click",function(event){
        if(event.result==false)
            return false;

        var module=$(this).closest(".gc-module").parent().closest(".gc-module").children("div[name=module-info]").text();
        var href=$(this).attr("href");
        if(href.indexOf(global_domain)!=-1&&href.replace(global_domain, "").split("/").length>=4) {
            ajaxUpdateSingleModule(module,href,"");
            event.preventDefault();
        }

        return true;
    });

    $("a.inline_action").bind("click",function(event){
        if(event.result==false)
            return false;

     
        var href=$(this).attr("href");
        var link = $(this);
        link.fadeTo("fast",0.5);
      
        if(href.indexOf(global_domain)!=-1&&href.replace(global_domain, "").split("/").length>=4) {
            ajaxUpdateModule(new Array("content"),href,"",new Array("content"),function(){
                link.fadeTo("fast",1);
            });
            event.preventDefault();
        }

        return true;
    });


    $("a.inline").bind("click",function(event){
        if(event.result==false)
            return false;
       
        var href=$(this).attr("href");

        if(href.indexOf(global_domain)!=-1&&href.replace(global_domain, "").split("/").length>=4) {
            ajaxUpdateContent(href,"");
            event.preventDefault();
        }
        return true;

    });

    /*.each(function(){
       
        var form=$(this).closest("form.inline");
        var href=form.attr("action");
        if(href==null||href==undefined||href=="")
            href=current_url;


        
  
        if(href.indexOf(global_domain)!=-1&&href.replace(global_domain, "").split("/").length>=4) {
            $(this).click(function (event)
            {
                event.preventDefault();
                var data=form.serialize();
             
                var currentData=data+(data!=""?"&":"")+this.name+"="+this.name;
                
                if(href.indexOf(base_url)!=-1) //Gleiche Seite
                    ajaxUpdateModule(new Array("content"),href,currentData);
                else
                    ajaxUpdateModule(new Array("content","menu/dynamic","user/head_userbox"),href,currentData);

            });
        }
    });
*/



    $(".gc-button").mouseover(function(){
        $(this).stop(true,true);$(this).fadeTo('fast',0.6)
    });
    $(".gc-button").mouseout(function(){
        $(this).stop(true,true);$(this).fadeTo('fast',1)
    });

    $("a.contentpopup").each(function(){
        $(this).unbind("click");
        $(this).colorbox({
            opacity:0.04,
            close:'Schließen',
            maxHeight:'500px',
            width:'570px',
            href:$(this).attr("href").toLowerCase().replace("/contentm/","/modulepopup/").replace("/content/","/popup/").replace("/seite/","/popup/"),
            title:$(this).attr("title")+' (<a href="'+$(this).attr("href")+'" title="Hier klicken, um dieses Fenster in einem eigenem Tab zu öffnen" target="_blank" onclick="$(\'#cboxClose\').click()">Vollansicht</a>)'
        },function(){
            fixPNGs();init_gui();do_onload();init_tooltip();
            $("#colorbox").draggable({
                handle:"#cboxTitle,#cboxTopLeft,#cboxTopCenter,#cboxTopRight,#cboxBottomLeft,#cboxBottomCenter,#cboxMiddleLeft,#cboxMiddleRight"
            }
            );
            $(".logo").resizable();

        });
    });

    $("a.adminpopup").each(function(){
        if($(this).attr("href")!=""&&$(this).attr("href")!="#"&&$(this).attr("href")!=undefined&&$(this).attr("href")!=null) {
            $(this).colorbox({
                opacity:0.04,
                close:'Schließen',
                href:$(this).attr("href").replace("/Admin/","/adminpopup/"),
                title:$(this).attr("title")+' (<a href="'+$(this).attr("href")+'" title="Hier klicken, um dieses Fenster in einem eigenem Tab zu öffnen" target="_blank" onclick="$(\'#cboxClose\').click()">Vollansicht</a>)'
            },function(){
                fixPNGs();init_gui();do_onload();init_tooltip();try{
                    tinyinit();
                }catch(ex){}
                $("#colorbox").draggable({
                    handle:"#cboxTitle,#cboxTopLeft,#cboxTopCenter,#cboxTopRight,#cboxBottomLeft,#cboxBottomCenter,#cboxBottomRight,#cboxMiddleLeft,#cboxMiddleRight"
                }
                );

            });
        }
    });

    initMenues();

    $(window).resize(function(){
        initMenues();
    });

}

function initMenues(){
    var id = 2345;
    $("form[name=suche] li a").each(function(){       
        var button = $(this).closest("form").children("."+$(this).attr("name"));
        
        button.addClass("but"+id);
        this.name = "but"+id;
        id++;
    });
    $(".dropdown").each(function(){
        $(this).menu({
            content: $(this).next().html(), // grab content from this page
            showSpeed: 400,
            width: 100
        });
    })
    $(".dropdown").show();
    $(".gc-quickbox_user").hide();
    
}

function toogleChangebox(){
    var infobox = $('.gc-head_userbox_info');
    var changebox = $('.gc-head_userbox_change');

    if(infobox.is(":visible")){

        setTimeout(function(){
            slideRight(changebox,infobox.width());
        },0);

        slideLeft(infobox);

    }else{
        setTimeout(function(){
            slideRight(infobox);
        },0);
        slideLeft(changebox);
    }

}

function slideLeft(obj){
    if(obj.data("blockslide")!=true){
        obj.data("blockslide",true);
        obj.data("oldwidth",obj.width())
        obj.animate({
            width:'0px'
        },300,'linear',function(){
            $(this).hide();
            obj.data("blockslide",false);
        });
    }
}

function slideRight(obj,width){
    if(obj.data("blockslide")!=true){
        obj.data("blockslide",true);
        var fullwidth=obj.data("oldwidth")!=undefined&&obj.data("oldwidth")!=null?obj.data("oldwidth"):width;
        obj.show();
        obj.animate({
            width:fullwidth
        },300,'linear',function(){
            obj.data("blockslide",false);
        });
    }
}


function ajaxHideOverlays(modules){
    $("div.ajaxOverlay").remove();
    if(typeof(modules)=="object"&&modules.length<=1)
        modules=new Array(modules);

         
    for(var current in modules){
         
        if(modules[current].html().indexOf("ajax?")!=0){
            var currentObj=modules[current];
            var moduleContent=currentObj.parent().children("div[name=module-content]");

            if(!moduleContent.is(":hidden"))
                moduleContent.fadeTo(0,1);
        }

    }
}

function ajaxShowOverlays(modules){
    if(typeof(modules)=="object")
        modules=new Array(modules);
    for(var current in modules){
        var currentObj=modules[current];
        var moduleName=currentObj.text();
        if(moduleName.indexOf("ajax_no_loadingimage=1")==-1){
            var moduleContent=currentObj.parent().children("div[name=module-content]");

            if(!moduleContent.is(":hidden")){
                moduleContent.css("display","block");
                moduleContent.fadeTo(0,0.5);

                var position=moduleContent.offset();
                var width=moduleContent.width();
                var height=moduleContent.height()

                var overlay=$('<div class="ajaxOverlay" style="position:absolute;top:'+position.top+'px;left:'+position.left+'px;z-index:990;width:'+width+'px;height:'+height+'px;"><img style="margin:auto;display:block;position:relative;top:'+(height/2-16)+'px" src="'+global_domain+'/img/ajax-loading.gif"/></div>');
                overlay.fadeTo(0,0.7);
                $("body").append(overlay);
            }
        }
    }
}


function ajaxExecuteRequest(action,requestData,successCallback,errorCallback,requestType) {
    var module = "ajax?action="+action;

    ajaxUpdateModule(module,current_url,requestData,"",successCallback,errorCallback,requestType);

}

function ajaxUpdateOuterModule(obj,url,postData){
    var module = $(obj).closest(".gc-module").children("div[name=module-info]").html();
    if(module.indexOf("?")>=0)
        module = module.substring(0,module.indexOf("?"))
    ajaxUpdateSingleModule(module,url,postData);
}

function ajaxUpdateSingleModule(module,url,postData) {
    
    if(url.indexOf("/content/")<0)
        if(module!="content"){
            ajaxUpdateModule(new Array("content",module),url,postData,new Array("content"));
        }else{
            ajaxUpdateModule(new Array("content",module),url,postData,new Array());
        }
    else
        ajaxUpdateModule(new Array(module),url,postData);

}

function ajaxUpdateContent(url,postData){
    if(url.indexOf(base_url)!=-1) //Gleiche Seite
        ajaxUpdateModule(new Array("content"),url,postData);
    else
        ajaxUpdateModule(new Array("content","menu/dynamic"),url,postData);
}

function escapeModule(module) {
    return escape(module).replace("/","_S_");
}

function ajaxUpdateModule(name,url,postData,noOutput,successCallback,errorCallback,requestType) {
    var noOutputModules=noOutput==undefined?new Array():noOutput;
    var updateUrl=url==undefined?current_url:url;
    var moduleNames=new Array("message");
    if(typeof name=="string")
        name=new Array(name);
    if(typeof noOutput=="string")
        noOutput=new Array(noOutput);
    var ajaxType=requestType;
 
    var data=postData==undefined?"":postData;
    if(data!="")
        data+="&";    

    moduleNames=name.concat(moduleNames);

    var moduleObjects=new Array();
    var modules="";
    $(".gc-module > div[name=module-info]").each(function(){
        var current=$(this).text();
      
        var currentObj=$(this);
        var toUpdate=false;
        for(var currentName in moduleNames){
            if(current.indexOf(moduleNames[currentName])==0){             
                toUpdate=true;
                break;
            }
        }
    
        if(toUpdate) {
            var showOverlay=true;
            for(var currentIgnore in noOutputModules){
                if(currentObj.html().indexOf(noOutputModules[currentIgnore])==0){
                    showOverlay=false
                    break;
                }
            }

            if(showOverlay)
                ajaxShowOverlays(currentObj)
            
            moduleObjects.push(currentObj);
            if(modules!="")
                modules+=",";
            modules+=escapeModule(current);
            
  
        }


    });

    if(moduleNames[0].indexOf("ajax?")==0){
       
        if(modules!="")
            modules+=",";
        modules+=escapeModule(name);
        var tmpObj = $("<div />");
  
        tmpObj[0].innerHTML=name;
        
        moduleObjects.push(tmpObj);
          
    }

    data+="show_single_module="+modules;

    $.ajax({
        dataType:ajaxType,
        type:"POST",
        url:updateUrl,
        data:data,
        success:function(data) {

            var loadedModules=data.split("<moduleSeperator/>");
          
            ajaxHideOverlays(moduleObjects);

            for(var x=0;x<loadedModules.length;x++) {

                var skip=false;
                if(successCallback!=undefined && moduleObjects[x].html().indexOf(name)==0){
                    successCallback($("div[name=module-content]",loadedModules[x]).html());
                }else{
                    for(var currentIgnore in noOutputModules){
                   
                        if(moduleObjects[x].html().indexOf(noOutputModules[currentIgnore])==0){
                            skip=true
                            break;
                        }
                    }

                    var moduleContent=moduleObjects[x].parent().children("div[name=module-content]");

                    if(!skip){
                        var newContent=$("div[name=module-content]",loadedModules[x]).html();

                        if(newContent!=undefined&&$.trim(newContent)!=""&&newContent!=null){
                            moduleContent.html(newContent);
                         
                        }
                    }

                   
                    if(moduleContent.children().length==1&&moduleContent.children("div")!=null)
                        moduleContent=moduleContent.children("div");
                    moduleContent.fadeTo(0,1);
                   
                

                }


                var sharpPos=updateUrl.lastIndexOf("#");
                if(sharpPos>=0){
                    var innerpageTarget=updateUrl.substring(sharpPos);
                    location.href=innerpageTarget;

                }
            }
           
            fixPNGs();do_onload();init_tooltip();init_gui();try{

                tinyinit();
            }catch(ex){}

        },
        error:function(XMLHttpRequest, textStatus, errorThrown){
            if(errorCallback!=undefined)
                errorCallback();
        }

    });
   

    


}

function submitForm(obj) {
    var form = $(obj).closest("form");
    if(form!=null&&form!=undefined) {
        var data=form.serialize();
        var url=form.attr("action")!=""&&form.attr("action")!=null&&form.attr("action")!=undefined?form.attr("action"):location.href;
        var module=$(obj).closest(".gc-module").find("div[name=module-info]").html();
        
        data+=(data && data.length > 0? "&":"")+$(obj).attr("name")+"=1";

        ajaxUpdateSingleModule(module,url,data);
        return true;
    }
    return false;
}

function gc_urlencode(url){
    return url.replace(/\s/g,"_");
}

function gc_getModule(name){
    var toFind = name;
    var result = null;
    $(".gc-module > div[name=module-info]").each(function(){
        var current=$(this).text();
        if(current.indexOf(toFind)!=-1){
            result = $(this).parent();
            return;
        }
        
    });
    return result;
}