var ajaxHandler = function(e){
    e.preventDefault();
    
    
    if ($(this).attr('href') == "/chat/startchat/") {
        chatWith($(this).attr('name'));
    }
    else {
    
        $.post($(this).attr('href'), {
            ajax: 1
        }, function(xml){
            $(document).netnalityParseAjax(xml);
            
        });
    }
    
    $('.tipsy').hide();
    
}







$.fn.netnalityParseAjax = function(xml){
    return this.each(function(){
    
        //alert(xml);
        
        $('response', xml).find('box').each(function(i){
        
        
        
            if (($(this).attr("action")) == "hide") {
                $('#' + ($(this).attr("id"))).hide('slow');
            }
            else 
                if (($(this).attr("action")) == "replace") {
                
                
                    $('#' + ($(this).attr("id"))).hide();
                    $('#' + ($(this).attr("id"))).html(($(this).find("html").text()));
                    $('#' + ($(this).attr("id"))).removeClass();
                    $('#' + ($(this).attr("id"))).addClass(($(this).find("class").text()));
                    $('#' + ($(this).attr("id"))).fadeIn();
                }
                else 
                    if (($(this).attr("action")) == "html") {
                        $('#' + ($(this).attr("id"))).html(($(this).find("html").text()));
                    }
                    else {
                        if (($(this).attr("action")) == "prepend") {
                            $('#' + ($(this).attr("prepend"))).prepend('<div class="' + $(this).find("class").text() + '" style="display: none;" id="' + $(this).attr("id") + '">' + $(this).find("html").text() + '</div>');
                            ;
                            $('#' + ($(this).attr("id"))).show('fast');
                            $('#' + ($(this).attr("prepend"))).removeClass('loading');
                        }
                        else 
                            if (($(this).attr("action")) == "append") {
                                $('#' + ($(this).attr("prepend"))).append('<div class="' + $(this).find("class").text() + '" style="display: none;" id="' + $(this).attr("id") + '">' + $(this).find("html").text() + '</div>');
                                ;
                                $('#' + ($(this).attr("id"))).show('fast');
                                $('#' + ($(this).attr("prepend"))).removeClass('loading');
                            }
                            else {
                                $('#' + ($(this).attr("id"))).hide('fast');
                                $('#' + ($(this).attr("id"))).html(($(this).find("html").text()));
                                $('#' + ($(this).attr("id"))).removeClass();
                                $('#' + ($(this).attr("id"))).addClass(($(this).find("class").text()));
                                $('#' + ($(this).attr("id"))).show('slow');
                            }
                    }
        });
        
        $('response', xml).find('input').each(function(i){
            $('#' + ($(this).attr("id"))).val($(this).text());
        });
        
        $('response', xml).find('messagebox').each(function(i){
			
			var options  = new Array();
			if($(this).attr("noclose")=='true') options.noclose=true;
			
			if($(this).attr("buttontext")) options.buttontext=$(this).attr("buttontext");

			if ($(this).find('buttonfunc').text()) 	options.buttonfunc = $(this).find('buttonfunc').text();
					
            $(document).netnalityMessageBox($(this).attr("title"), $(this).find('text').text(), options);
        });
        
        if ($('response', xml).find('redirect').text()) {
            window.location.replace($('response', xml).find('redirect').text());
        }
		
        if ($('response', xml).find('javascript').text()) {
            eval($('response', xml).find('javascript').text());
        }		
        
        
        
        if ($('response', xml).find('personalactivity').text()) {
        
        
            if ($('response', xml).find('personalactivity').text() > 0) {
                $('#personalactivityButton a img').effect("pulsate", {
                    times: 3
                }, 2000);
                
				document.title = '(' + $('personalactivity').text() + ') '+  originalTitle;
				
                if($('response', xml).find('personalactivity').text() == '1') {$('#personalactivityButton a').attr('title', 'Ein neues Ereignis')}
                else {$('#personalactivityButton a').attr('title', $('response', xml).find('personalactivity').text() + ' neue Ereignisse')}
                $('#personalactivityButton a').trigger('mouseenter');
                
            }
            
            $("#chatButton a").click(chatButtonHandler);
            
        }
        
        $('response', xml).find('facebox').each(function(i){
            if (($(this).attr("action")) == "close") {
                jQuery(document).trigger('close.facebox');
                
            }
        });
        
        $("a[rel*=ajax]").unbind("click");
        
        $('a[rel*=ajax]').click(ajaxHandler);
        
        
        
        
        $("a[rel*=facebox]").unbind("click");
        
        jQuery('a[rel*=facebox]').facebox()
        
        $('.tooltip').tipsy({
            gravity: 's',
            fade: true
        });
        $('.tooltipright').tipsy({
            gravity: 'w',
            fade: true
        });
        $('.tooltipleft').tipsy({
            gravity: 'e',
            fade: true
        });		
        
        
    });
};


$.fn.netnalityMessageBox = function(title, text, options){

    var html = ' \
	<div id="title">';
    
    if (options.noclose != true) {
        html = html + '<div class="close"> \
        <a href="#"><img width="15" height="15" src="/images/facebox/closelabel_white.gif" alt="Schließen" title="Schließen" /></a> \
    </div>';
    }
    
    html = html + '<h2>' + title + '</h2> \
	</div> \
	<div id="content"> \
	 ' +
    text +
    '\
	</div><div id="bottom"> ';
    
    if (options.buttontext && options.buttonfunc) {
        html = html + '<a class="buttonStandard buttonStrong" id="action" href="">' + options.buttontext + '</a>';
    }
    
    if (options.noclose != true) {
        html = html + '<a class="buttonStandard" id="cancel" href="">Abbrechen</a>';
    }
    
    html = html + '</div>';
    
    jQuery.facebox(html);
    
    
    
    $(".close a").click(function(e){
        e.preventDefault();
        jQuery(document).trigger('close.facebox');
        
    });
    
    $("#cancel").click(function(e){
        e.preventDefault();
        jQuery(document).trigger('close.facebox');
        
    });
    
    if (options.buttontext && options.buttonfunc) {
    
	
	
		if(typeof options.buttonfunc == 'string') {
			
			$("#action").click(function(){
				eval(options.buttonfunc)
			});
		}
		else {
			$("#action").click(options.buttonfunc);
		}
		
        
        
        $("#action").click(function(e){
            e.preventDefault();
            jQuery(document).trigger('close.facebox');
            
        });
    }
    
    
}

$.log = function(message){
    if (window.console) {
        console.debug(message);
    }
    else {
        alert(message);
    }
};


jQuery(document).ready(function(){

	originalTitle = document.title;
	
    
    $([window, document]).blur(function(){
        windowFocus = false;
    }).focus(function(){
        windowFocus = true;
        document.title = originalTitle;
    });	



    $('a[rel*=ajax]').click(ajaxHandler);
    
    
    jQuery('a[rel*=facebox]').facebox()
    
    
    $("#loading").ajaxStart(function(){
        $(this).fadeIn();
    });
    $("#loading").ajaxStop(function(){
        $(this).fadeOut();
    });
    
    
    
    $('.tooltip').tipsy({
        gravity: 's',
        fade: true
    });
    $('.tooltipright').tipsy({
        gravity: 'w',
        fade: true
    });
    $('.tooltipleft').tipsy({
        gravity: 'e',
        fade: true
    });
    	
    
    //$('#personalactivityButton a').tipsy({gravity: 'e', fade: true});
    
    
    
    
    $('a[href!=""]').click(function(){
        $("#loading").fadeIn();
    });
    
    $('a[href*=#]').click(function(){
        $("#loading").fadeOut();
    });
    
    $("#loading").fadeOut();
    
});





$(document).ready(function(){
	
	


    $("#personalactivityButton a").click(function(e, fast){
    
        e.preventDefault();
        
        
        $("#personalactivityButton").toggleClass("current");
        
        if ($("#personalactivityButton").is('.current')) {
        
        
            if ($("#chatButton").is('.current')) {
                $('#chatButton a').trigger('click', true);
            }
            
            $.post('/eventlog/', {
                ajax: 1
            }, function(xml){
                $(document).netnalityParseAjax(xml);
                $('#personalactivity').css({
                    left: $('#personalactivityBar').offset().left
                });
                $('#personalactivity').css({
                    top: $('#personalactivityBar').offset().top - $('#personalactivity').height() - 12
                });
                
                //$('#personalactivity').width($('#personalactivityBar').width() + $('#personalactivityButton').width() );
                
                $('#personalactivity').width($('#personalactivityButton').offset().left - $('#personalactivityBar').offset().left + 8);
                
                
                $('#personalactivity .blink').effect("pulsate", {
                    times: 30
   				}, 1000);
				
				$("#personalactivity .deleteEvent").click(function(e){
					e.preventDefault();
					var event = $(this).parent();
					
					
					var id = event.attr("id");
																												
									
					$.post("/eventlog/", {
						deleteevent: id,
						ajax: 1
					}, function(xml){						
						$(document).netnalityParseAjax(xml);
					});
					
				});
				
				$(".personalactivityRow a").click(function(e){
					
			
					if ($(this).hasClass('deleteEvent') != true) {
						e.preventDefault();
						var event = $(this).parent();
						var href = $(this).attr('href');
						
						
						$.post("/eventlog/", {
							deleteevent: event.attr("id"),
							ajax: 1
						}, function(xml){							
							window.location.replace(href);
						});
						
					}
					
								
				});													
                
                $('#personalactivityButton a').trigger('mouseout');
                
				
				
            });
            
            
        }
        else {
            if (fast == true) {
                $("#personalactivity").hide();
                $("#personalactivityBar").hide();
            }
            else {
                $("#personalactivity").fadeOut();
                $("#personalactivityBar").fadeOut();
            }
        }
        
        
    });
    
    
    
    
    
    
    
    
    
    
    
});


var chatButtonHandler = function(e, fast){

    e.preventDefault();
    
    
    $("#chatButton").toggleClass("current");
    
    if ($("#chatButton").is('.current')) {
    
        if ($("#personalactivityButton").is('.current')) {
            $('#personalactivityButton a').trigger('click', true);
        }
        
        $("#chat").fadeIn();
        $("#chatBar").fadeIn();
        
        $('#chat').css({
            left: $('#chatBar').offset().left
        });
        $('#chat').css({
            top: $('#chatBar').offset().top - $('#chat').height() - 2
        });
        
        
        $('#chat').width($('#personalactivityButton').offset().left - $('#chatBar').offset().left + 28);
        
        
        
        $('#chatButton a').trigger('mouseout');
        
        
        
        
    }
    else {
        if (fast == true) {
            $("#chat").hide();
            $("#chatBar").hide();
        }
        else {
            $("#chat").fadeOut();
            $("#chatBar").fadeOut();
        }
    }
    
    
};


$.fn.selectRange = function(start, end){
    return this.each(function(){
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        }
        else 
            if (this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            }
    });
};





(function($){
    // IE DOMParser wrapper
    if (window['DOMParser'] == undefined && window.ActiveXObject) {
        DOMParser = function(){
        };
        DOMParser.prototype.parseFromString = function(xmlString){
            var doc = new ActiveXObject('Microsoft.XMLDOM');
            doc.async = 'false';
            doc.loadXML(xmlString);
            return doc;
        };
    }
    
    $.xmlDOM = function(xml, onErrorFn){
        try {
            var xmlDoc = (new DOMParser()).parseFromString(xml, 'text/xml');
            if ($.isXMLDoc(xmlDoc)) {
                var err = $('parsererror', xmlDoc);
                if (err.length == 1) {
                    throw ('Error: ' + $(xmlDoc).text());
                }
            }
            else {
                throw ('Unable to parse XML');
            }
        } 
        catch (e) {
            var msg = (e.name == undefined ? e : e.name + ': ' + e.message);
            if ($.isFunction(onErrorFn)) {
                onErrorFn(msg);
            }
            else {
                $(document).trigger('xmlParseError', [msg]);
            }
            return $([]);
        }
        return $(xmlDoc);
    };
})(jQuery);


