(function($) {

    /**
     * Öffnet die Lightbox
     * @param obj Object a Tag, img Tag, canvas, jsonString
     */
    window.lightbox = function( obj ) {

		var loadedAjaxLinks = 0;

        /**
         * Ermittelt den Title Tag
         * @param $item jQuery Object
         * @param JSON json
         */
        var getKeyVal = function( keyVal,  $item , json ) {
            var title = "";
            if( json.valid )
            {
                for( key in json.data )
                {
                    if( $item.attr('rel') == null || $item.attr('rel').indexOf('no-'+key) == -1 )
                    {
                        value = json.data[key];

//                        if( key == keyVal && titleName != null && titleName.length > 1 )
//                        {
//                            value = titleName;
//                        }
                        if( key == 'source' && value != null && value.length > 1 )
                            value = 'Quelle: ' + value;
                        title += '<span class="'+key+'">' + value + '</span>';
                    }
                }
            }
            return title;
        };

        /**
         * jQuery Deferred Function!
         * @param $item jQuery Object or string
         * @param callback function ( erhält ein Array mit href und titel )
         * @return Deferred.promise()
         */
        var getLightboxData = function($item, callback) {

            var dfd = $.Deferred();

            // $item ist eine id
            if( typeof $item == "string" && $item.charAt(0) == '#') {
                $item = $($item);
            }

            if( typeof $item == "object" && $item.isJSON == true )
            {
                var title = "";
                for( key in $item.data )
                {
                    if( $item.data[key] != null )
                    {
                        title += '<span class="'+key+'">' + $item.data[key] + '</span>';
                    }
                }
                dfd.resolve();
				//title += '<span class="source">'+ $item.data['source'] +'</span>';
                if( typeof callback == "function" )
                    callback( [ $item.src, title ] );
				loadedAjaxLinks++;
                return dfd.promise();
            }
            else if( $item.is('a') )
            {
                href = $item.attr('href');
                titleName = $item.find('img').attr('title');
                imageName = $item.find('img').attr('src');
            }
            else if( $item.is('img') )
            {
                href = $item.attr('src').replace(/\/\.\d\//,"/.2/");
                titleName = $item.attr('title');
                imageName = $item.attr('src');
            }
            else if( $item.is('canvas') )
            {
                href = $item.attr('src').replace(/\/\.\d\//,"/.2/");
                imageName = $item.attr('src');
                titleName = null;
            }


            if( $item.data('ajaxdata') != undefined )
            {
                title = getKeyVal( 'title', $item,$item.data('ajaxdata'));
				//title += getKeyVal( 'source', $item,$item.data('ajaxdata'));
                dfd.resolve();
                if( typeof callback == "function" )
                    callback( [ href, title ] );
				loadedAjaxLinks++;
				return dfd.promise();
            }
            else
            {
                $.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    async: true,
                    data: {
                        'action': 'lightbox_getInfo',
                        'image': imageName
                    },
                    success: function(json){
                        title = getKeyVal('title',$item,json);
						//title += '<span class="source">'+ getKeyVal( 'source', $item,$item.data('ajaxdata')) +'</span>';
                        $item.data('ajaxdata',json);
                        dfd.resolve();

                        if( typeof callback == "function" )
                            callback( [ href, title ] );

						loadedAjaxLinks++;
                    },
                    dataType: 'json'
                });
            }

            return dfd.promise();
        };

        /**
         * Übergibt die Links an die definierte Lightbox
         * @param links array
         * @param int clickedImageIndex
         * @return void
         */
        var openLightbox = function( links, clickedImageIndex ) {
            jQuery.fancybox(links,{
                'titlePosition' : 'inside',
                'index': clickedImageIndex
            });
            window.setTimeout(function(){
                jQuery('#fancybox-img').attr('title','');
                jQuery('#fancybox-img').attr('alt','');
            }, 500);
        };

		/**
		 * Wird beim $.when().then() aufgerufen
		 */
		var defferedComplete = function(clickedImageIndex){

			// Items neuladen
			items = $('[rel="'+$item.attr('rel')+'"]');

			if( loadedAjaxLinks !=  items.length )
			{
				window.setTimeout(function(){
					defferedComplete(clickedImageIndex);
				},250);
				return;
			}

			// Die zuvor geladen daten neu auslesen
			$.each(items,function(){
				getLightboxData($(this),function(data){
					links.push({
						'href'	: data[0],
						'title'	: data[1]
					});
				});
			});

			openLightbox(links, clickedImageIndex);
		}

        var links = [];
        var clickedImageIndex = 0;

        // Manueller aufruf über ein Json Object
        if( typeof obj == 'string' && jQuery.parseJSON(obj) != null )
        {
            var json = jQuery.parseJSON(obj);

            $.each(json,function(){
                this.isJSON = true;
                getLightboxData(this,function(data){
                    links.push({
                        'href': data[0],
                        'title': data[1]
                    })
                });
            });

            openLightbox( links, clickedImageIndex );
            return;
        }
        else
        {
            var $item = $(obj);
            var href,title,imageName;

            var lightboxRegex = /(.*?)\[([\w\d-_]+)\]/;

            // Galerie öffnen
            if( $item.attr('rel') != null && (matchResult = $item.attr('rel').match(lightboxRegex)) )
            {
                // Alle Galeriebilder
                var items = $('[rel="'+$item.attr('rel')+'"]');
                // Geklicktes Bild
                clickedImageIndex = $(items).index( $item );


                var funcs = [];
                $.each(items,function(index,element){
                    var id = 'image_'+matchResult[2]+'_'+index;
                    $(this).attr('id',id);
                    funcs.push('getLightboxData("#'+id+'")');
                });
                var data = funcs.join(", ");

                // Alle Bilder daten laden mit der getLightboxData Funktion, und dann...
                $.when( eval(data) ).then(function(){defferedComplete(clickedImageIndex)});
            }
            // Einzelnes Bild
            else
            {
                getLightboxData($item,function(data){
                    links = [{
                        'href'	: data[0],
                        'title'	: data[1]
                    }];
                    openLightbox( links, clickedImageIndex );
                });
            }
        }
    }

    /**
     * Clone an input with another type
     * @param string newType
     * @param object originalInput
     */
    window.cloneInput = function( type , originalInput ) {
        var inp = $('<input type="'+type+'" />');

        inp.addClass( $(originalInput).attr('class') );
        inp.attr( 'name', $(originalInput).attr('name') );
        inp.attr( 'value', $(originalInput).attr('value') );
        return inp;
    }

    /**
     * Change the default value of an Input Button or an Password field on focus
     * @param jquery targets
     */
    window.infieldLabel = function( targets ) {
        $(targets).live('focusin',function(){
            if($(this).data("oldvalue") == null || $(this).data("oldvalue") == $(this).val())
            {
                $(this).data("oldvalue",$(this).val());
                $(this).val("");
                if($(this).data("oldtype") == "password" )
                {
                    var newObj = cloneInput('password', this );
                    newObj.data("oldtype","password");
                    newObj.data("oldvalue", $(this).data('oldvalue') );
                    $(this).replaceWith( newObj );
                    window.setTimeout(function(){
                        newObj.focus();
                    },500);
                }
            }
        }).live('focusout',function(){
            if($(this).val() == "")
            {
                $(this).val($(this).data("oldvalue"));
                if($(this).data("oldtype") == "password" )
                {
                    var newObj = cloneInput('text', this );
                    newObj.data("oldtype","password");
                    newObj.data("oldvalue", $(this).data('oldvalue') );
                    $(this).replaceWith( newObj );
                }
            }
        }).each(function(){
            if( $(this).attr('type') == 'password' )
            {
                var newObj = cloneInput('text', this );
                newObj.data("oldtype","password");
                newObj.data("oldvalue", $(this).data('oldvalue') );
                $(this).replaceWith( newObj );
            }
        });
    }

    /**
     * Writes the Flash Object code
     * @param string filename
     * @param string filename_bild
     * @param int width
     * @param int height
     * @param bool transparent
     * @param int qualitaet
     */
    window.getFlash = function(filename, filename_bild, width, height, transparent, qualitaet)
    {
        var objectData = '<object type="application/x-shockwave-flash" data="'+filename+'" width="'+width+'" height="'+height+'">';

        if (transparent == true)
        {
            objectData += '<param name="wmode" value="transparent">';
        } else {
            objectData += '<param name="wmode" value="opaque">';
        }

        objectData += '<param name="movie" value="'+filename+'">';
        objectData += '<param name="quality" value="'+qualitaet+'">';
        objectData += '<img src="'+filename_bild+'" width="'+width+'" height="'+height+'" border="0" />';
        objectData += '</object>';
        document.write(objectData);
    }


    window.addToFavorites = function()
    {
        var url = window.location.href;
        var text = document.title;

        if (window.sidebar) {
            // firefox
            window.sidebar.addPanel(text,url, "");
        }else if(window.opera && window.print) {
            // opera
            var elem = document.createElement('a');
            elem.setAttribute('href',url);
            elem.setAttribute('title',text);
            elem.setAttribute('rel','sidebar');
            elem.click();
        }else if(document.all){
            // ie
            window.external.AddFavorite(url,text);
        }else{
            alert("Drücken Sie 'STRG' + 'D' um diese Seite zu den Favoriten hinzuzufügen");
        }
    }


    $(function(){

        infieldLabel("#header input[type=text],#header input[type=password]");

        $("a[rel^='lightbox'],img[class*='open_lightbox']").bind('click',function(event){
            event.preventDefault();
            lightbox( this );
            return false;
        }).css('cursor','pointer');

        /*
		$('.toggle_item').hide();
		$('.toggle_link').click(function() {
			$('.toggle_item').toggle('slow');
		}).css('cursor','pointer');
		*/

		$('[class^=toggle_item_]').hide();
		$('[class^=toggle_link_]').click(function() {
			var x = $(this).attr("class");
			$('.toggle_item_' + x.substr(12)).toggle('slow');
			return false;
		}).css('cursor','pointer');

		$('table.zebra tbody tr:even').addClass('zeile_1');
		$('table.zebra tr:odd').addClass('zeile_2');

    });

})(jQuery);

function mitarb_toggle(id) {
	$j('#mitarb_'+id).toggle("slow");
}
