/**
 * Safer console.log(). Just use log()!
 */
window.log = function(){
    log.history = log.history || [];
    log.history.push(arguments);
    arguments.callee = arguments.callee.caller;
    if(this.console) console.log( Array.prototype.slice.call(arguments) );
};
(function(b){
    function c(){}
    for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c
        })(window.console=window.console||{});

(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 getTitle = function( $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 == 'title' && titleName != null )
                        {
                            value = titleName;
                        }
                        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();
                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 = getTitle($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 = getTitle($item,json);
                        $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
            });
        };

		/**
		 * 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(){
                console.log(this);
                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');

    });

    $(function() {
        $('a.iframe').fancybox({
            'centerOnScroll' : true,
            'scrolling': 'no',
            'onComplete' : function() {
                setTimeout(function() {
                    resize();
                }, 1000);
            },
            'type' : 'iframe'
        });

        function resize() {
            var outer = $('#fancybox-wrap');
            var inner = $('#fancybox-content');

            var newHeight = $('#fancybox-frame').contents().find('html').height();
            var newWidth = $('#fancybox-frame').contents().find('html').width();

            var extra = 20;

            if(newHeight > 0 && newWidth > 0) {
                outer.css({
                        height: newHeight + extra,
                        width: newWidth + extra
                });
                inner.css({
                        height: newHeight + extra,
                        width: newWidth + extra
                });
                $.fancybox.center();
            }
        }
    });




})(jQuery);
