var csl = {



    /**
     * default value for the document language
     */
    docLang: 'de',



    /**
     * initialize
     */
    initialise: function() {
        this.setDocLang();
        this.fx.initialise();
        this.microformats.initialise();
        this.fixIE6();
		this.observeTargetBlankLinks();
		this.advertisingThemes();
    },



    /**
     * try to determine the document language
     * 1. from the 'xml:lang' attribute of the opening html tag
     * 2. from the 'lang' attribute of the opening html tag
     * 3. from the 'class' attribute of the opening body tag
     * if none if these attributes is filled with a valid value, the default value is used
     */
    setDocLang : function() {
        var lang = $('html').attr('xml:lang') || $('html').attr('lang') || ( $('body[class^=lang_]') ? $('body').attr('class') : csl.docLang ) || csl.docLang;
        if ( lang.match(/.?lang\_(\w*).?/g) ) lang = RegExp.$1;
        if ( lang.length > 2 ) lang = lang.substring(0, 2);
        csl.docLang = lang;
    },



    /**
     * fix some IE6 bugs
     * especially fixes for the transparent png bug
     */
    fixIE6 : function() {
        if (!$.browser.msie) return;
        $('.infosToGo img, blockquote p img').ifixpng();
        $('#teamlist li').ifixpng();
        $('.infosToGo img').css({ width: '43px', height: '53px' });
    },



    /**
     * visual effects
     */
    fx : {



        /**
         * enhance ...
         */
        initialise: function() {
            this.selectLanguage();
            this.searchField();
            this.sevenloadUserData();
            this.teamList.initialise();
            this.trademarks.initialise();
        },



        /**
         * ... the language selector
         */
        selectLanguage: function() {

            /* rebuild the html, transform <select> to <ul> */
            $('#languageSelector option').map(function() {
               $(this).replaceWith('<li' + ($(this).hasClass('selected') ? ' class="selected"' : '') + '><a href="' + $(this).val() + '" hreflang="' + $(this).attr('title') + '">' + $(this).text() + '</a></li>');
            });
            $('form#languageSelector').replaceWith('<ul id="languageSelector">' + $('form#languageSelector select').html() + '</ul>');

            /* show/hide the whole list on mouseover/-out */
            $('ul#languageSelector').mouseover(function() {
                $(this).addClass('focused');
            });
            $('ul#languageSelector').mouseout(function() {
                $(this).removeClass('focused');
            });

            $('#languageSelector, #languageSelector .selected').ifixpng();
        },



        /**
         * ... the search field
         */
        searchField: function() {
            $('#searchtext').focus(function() {
                oldSearchText = $(this).attr('value');
                $(this).attr('value', '');
            });
            $('#searchtext').blur(function() {
                $(this).attr('value', oldSearchText);
            });
        },



        /**
         * ... the sevenload user datatable
         */
        sevenloadUserData: function() {

            if ( !$('sevenloaduser_data') ) return;

            animateMe = function(tbody) {
                jQuery.each( tbody.find('var'), function(){
                    var width = $(this).html().replace(' %','');
                    var padding = width*5.5;
                    $(this).prev('span').animate(
                        { 'paddingLeft': padding }
                        ,1000
                        ,function() {
                            if ($(tbody).next('tbody').size() > 0) {
                                animateMe( $(tbody).next('tbody') );
                            }
                        }
                    );
                });
            }

            animateMe( $('#sevenloaduser_data').find('tbody:first') );
        },



        /**
         * ... the team listing
         */
        teamList: {

            /**
             * the three columns
             */
            cols: {
                className: Array ( 'leftCol', 'middleCol', 'rightCol' ), // classnames
                
                leftCoor: { // left positions in pixel
                    normal: Array ( 0, 204, 408 ), // normal position
                    hovered: Array ( 0, 150, 325 ) // position when hovered
                },

                nullPos: { // the css styles of the vcards, that are filtered out
                    'opacity': '0',
                    'top': '17px',
                    'left': '0px'
                }
            },

            height: 100,        // the height of a vcard in pixel
            margin: 27,         // the margin between the vcards in pixel
            animations: false,  // some animations will be deactivated when this var is FALSE
            aniTime: 250,       // the animation speed in milli seconds



            /**
             * the various department texts in different languages
             */
            texts: {
                'de': {
                    departments: { // the department names
                        'dep_sales': 'Sales',
                        'dep_design': 'Design',
                        'dep_management': 'Management',
                        'dep_international': 'International',
                        'dep_technik': 'Technik',
                        'dep_communication': 'Kommunikation',
                        'dep_content': 'Content',
                        'team': 'Team'
                    },
                    sublines: { // the department sublines
                        'dep_sales': 'Marken / Produkte',
                        'dep_design': 'Grafik / Layout',
                        'dep_management': 'Management',
                        'dep_international': 'Internationalisierung',
                        'dep_technik': 'Server / Flash / API',
                        'dep_communication': 'Social Media / Public Rel.',
                        'dep_content': 'Marken / Produkte',
                        'team': 'alle Teammitglieder'
                    },
                    titles: { // the text for the title attribute
                        'dep_sales': 'Nur die Mitglieder des Teams Sales anzeigen.',
                        'dep_design': 'Nur die Mitglieder des Teams Design anzeigen.',
                        'dep_management': 'Nur die Mitglieder des Teams Management anzeigen.',
                        'dep_international': 'Nur die Mitglieder des Teams International anzeigen.',
                        'dep_technik': 'Nur die Mitglieder des Teams Technik anzeigen.',
                        'dep_communication': 'Nur die Mitglieder des Teams Kommunikation anzeigen.',
                        'dep_content': 'Nur Mitglieder des Teams Content anzeigen.',
                        'team': 'Alle Teammitglieder anzeigen.'
                    }
                },
                'en': {
                    departments: { // the department names
                        'dep_sales': 'Sales',
                        'dep_design': 'Design',
                        'dep_management': 'Management',
                        'dep_international': 'International',
                        'dep_technik': 'Technology',
                        'dep_communication': 'Communication',
                        'dep_content': 'Content',
                        'team': 'Team'
                    },
                    sublines: { // the department sublines
                        'dep_sales': 'Sales',
                        'dep_design': 'Design',
                        'dep_management': 'Management',
                        'dep_international': 'International',
                        'dep_technik': 'Technology',
                        'dep_communication': 'Communication',
                        'dep_content': 'Content',
                        'team': 'all team members'
                    },
                    titles: { // the text for the title attribute
                        'dep_sales': 'Show only members of the Sales team.',
                        'dep_design': 'Show only members of the Design team.',
                        'dep_management': 'Show only members of the Management team.',
                        'dep_international': 'Show only members of the International team.',
                        'dep_technik': 'Show only members of the Technology team.',
                        'dep_communication': 'Show only members of the Communication team.',
                        'dep_content': 'Show only members of the Content team.',
                        'team': 'Show all team members.'
                    }
                }
            },



            /**
             * calculating the positions of the list items and let them fly in
             * @param (String) elList: css selector to define the elements
             * @param (Integer) newTime: animation speed in milli seconds
             */
            flyIn: function(elList, speed) {
                var that = csl.fx.teamList;
                var speed = speed || 1000;
                var topCoor = -110;

                $('#teamlist').addClass('filtering').css({
                    'height': Math.ceil(($(elList).size()/3)) * (that.height+that.margin) + that.margin+'px'
                });
                jQuery.each( $(elList), function(i){
                    // stop all pending animations on the vcard and set its classNames
                    $(this).stop().removeClass('out '+that.cols.className.join(' ')).css('zIndex', 10);

                    // calculate the absolute top position
                    topCoor = i % 3 == 0 ? topCoor + that.height + that.margin : topCoor;

                    // move the vcard to its calculated absolute position
                    $(this).animate({ 
                    	top: topCoor + 'px',
                    	left: that.cols.leftCoor.normal[i%3] + 'px',
                    	opacity: '1'
                    }, speed, function(){
                        $(this).addClass( that.cols.className[i%3] );
                        $('#teamlist').removeClass('filtering');
                    });
                });
            },



            /**
             * building the filter list
             */
            filterList: function() {
                var that = csl.fx.teamList;

                /**
                 * read the used departments in the vcards and build the html markup for the filter list
                 */
                var deps= Array();
                $('#teamlist li').each(function(n){
                    var dep = $(this).attr('class').replace(/vcard /g, '');
                    if (jQuery.inArray(dep, deps) === -1) deps.push(dep);
                });
                deps.push('team');
                $('#content h2').after('<ul id="depFilter" class="cleared"></ul>');
                for (d in deps) {
                    $('#depFilter').append('<li><a rel="'+(deps[d]!='team'?deps[d]:'')+'" href="#" title="'+that.texts[csl.docLang].titles[deps[d]]+'">'+that.texts[csl.docLang].departments[deps[d]]+'<span>'+that.texts[csl.docLang].sublines[deps[d]]+'</span></a></li>');
                }


                /**
                 * when a filter link is clicked
                 */
                $('#depFilter a').click(function(evt){
                    evt.preventDefault();
                    $('#teamlist').addClass('filtering');
                    if ( !$(this).hasClass('filtered') ) {
                        var filter = $(this).attr('rel') != '' ? '.'+$(this).attr('rel') : '';

                        // set some classes
                        (filter != '') ? $('#teamlist').addClass('filtered') : $('#teamlist').removeClass('filtered');
                        $('#depFilter a.filtered').removeClass('filtered');
                        $(this).addClass('filtered');

                        // fade out the filtered vcards
                        if (filter != '') {
                            if (that.animations) {
                                $('#teamlist li:not('+filter+')').animate(that.cols.nullPos, that.aniTime*2, function() {
                                    $(this).addClass('out');
                                });
                            } else {
                                $('#teamlist li:not('+filter+')').css(that.cols.nullPos).addClass('out');
                            }
                        }

                        $('#teamlist li'+filter).removeClass('out').show();
                        $('#depFilter li.selected').removeClass('selected');
                        $(this).parent('li').addClass('selected');

                        // let the rest of the vcards fly to its new position
                        that.flyIn($('#teamlist li'+filter), that.aniTime*3);
                    } else {

                        // show all vcards and let them fly in
                        $(this).removeClass('filtered');
                        $('#teamlist').removeClass('filtered');
                        $(this).parent('li').removeClass('selected');
                        that.flyIn($('#teamlist li'), that.aniTime*3);
                    }
                });


                /**
                 * highlighting the corresponding vcards when the mouse moves over a filter link
                 */
                $('#depFilter a').mouseover(function(evt){
                    evt.preventDefault();
                    var filter = $(this).attr('rel') != '' ? '.'+$(this).attr('rel') : '';

                    if (that.animations) {
                        if (filter != '') $('#teamlist li:not('+filter+'):not(.out)').animate({'opacity': .25}, that.aniTime/4);
                        $('#teamlist li'+filter+':not(.out)').animate({'backgroundPosition': '0px 0px'}, that.aniTime/4);
                    } else {
                        if (filter != '') $('#teamlist li:not('+filter+'):not(.out)').css({'opacity': .25});
                        $('#teamlist li'+filter+':not(.out)').css({'backgroundPosition': '0px 0px'});
                    }
                });


                /**
                 * de-highlighting the corresponding vcards when the mouse leaves the hovered filter link
                 */
                $('#depFilter a').mouseleave(function(evt){
                    evt.preventDefault();
                    var filter = $(this).attr('rel') != '' ? '.'+$(this).attr('rel') : '';
                    if (that.animations) {
                        $('#teamlist li'+(filter!=''?':not('+filter+')':'')+':not(.out)').animate({'opacity': 1}, that.aniTime/4);
                        $('#teamlist li'+filter+':not(.out)').animate({'backgroundPosition': '-3px -3px'}, that.aniTime/4);
                    } else {
                        $('#teamlist li'+(filter!=''?':not('+filter+')':'')+':not(.out)').css({'opacity': 1});
                        $('#teamlist li'+filter+':not(.out)').css({'backgroundPosition': '-3px -3px'});
                    }
                });
            },



            /**
             * @description: when the mouse enters a vcard, this vcard will be hightlighted and all other vcards will be faded out
             * @param: (Event) evt: the triggered Event
             */
            vcardHover: function(evt){
                var that = csl.fx.teamList;

                // fading out my siblings
                if ( $('#teamlist').hasClass('filtering') ) return;
                if (that.animations) {
                    $('#teamlist li:not(.out)').stop().animate({'opacity': .25}, that.aniTime/3).css('zIndex', 0);
                } else {
                    $('#teamlist li:not(.out)').stop().css({'opacity': .25, 'zIndex': 0});
                }
                $(this).siblings('.hovered').removeClass('hovered');

                // zooming me in
                $(this).stop().css({
                    left: $(this).hasClass(that.cols.className[1]) ? that.cols.leftCoor.hovered[1] : $(this).hasClass(that.cols.className[2]) ? that.cols.leftCoor.hovered[2] : $(this).css('left'),
                    zIndex: 10,
                    'opacity': 1
                }).addClass('hovered');

                // highlighting the corresponding department
                var dep = jQuery.trim($(this).attr('class').match(/dep\_(.*?)\s/)[0]);
                $('#depFilter li a[rel='+dep+']').addClass('filtered');
                $('#depFilter li a[rel='+dep+']').parent('li').addClass('selected');
            },



            /**
             * @description: when the mouse leaves a vcard, all vcards will be displayed normally
             * @param: (Event) evt: the triggered Event
             */
            vcardOut: function(evt){
                var that = csl.fx.teamList;

                // fading in my siblings
                if ( $('#teamlist').hasClass('filtering') ) return;
                if (that.animations) {
                    $('#teamlist li:not(.out)').stop().animate({'opacity': 1}, that.aniTime/2).css('zIndex', 0);
                } else {
                    $('#teamlist li:not(.out)').stop().css({'opacity': 1, 'zIndex': 0});
                }

                // zooming me out
                $(this).stop().css({
                    left: $(this).hasClass(that.cols.className[1]) ? that.cols.leftCoor.normal[1] : $(this).hasClass(that.cols.className[2]) ? that.cols.leftCoor.normal[2] : $(this).css('left')
                }).removeClass('hovered');

                // disabling the highlight effect of the corresponding department
                var dep = jQuery.trim($(this).attr('class').match(/dep\_(.*?)\s/)[0]);
                if ( !$('#teamlist').hasClass('filtered') ) {
                    $('#depFilter li a[rel='+dep+']').removeClass('filtered');
                    $('#depFilter li a[rel='+dep+']').parent('li').removeClass('selected');
                }
            },



            /**
             * initialising the team list
             */
            initialise: function() {
                if ( !document.getElementById('teamlist') ) return;

                var that = csl.fx.teamList;

                // try to determine the browser engine and activate all animations for safari
                if ($.browser.safari) that.animations = true;

                // setting the initial classes and styles for the list
                $('#teamlist').addClass('activating').css({
                    'position': 'relative',
                    'margin': '0px'
                });

                // rebuilding the filter list
                this.filterList();

                // binding the eventHandlers of the vcards
                $('#teamlist li').bind('mouseenter', that.vcardHover).bind('mouseleave', that.vcardOut);

                // letting all vcards fly in
                this.flyIn($('#teamlist li'), this.aniTime*4);
                $('#teamlist').removeClass('activating').addClass('activated');

            } // end of method "initialise"

        }, // end of object "teamlist"



		/**
		 * animation of the trademark logos
		 */
        trademarks: {

			// animation parameters (styles before and after the animation; animation duration)
            startPos: {},
            endPos: { left: 130, top: 70, opacity: 1 },
            duration: 500,


			// prepare the trademark logos
            initialise: function() {
                if ( $('.trademarks').size() == 0 ) return;
                this.animate();
            },


			// animate the trademark logos to show additional infos
            animate: function() {
                that = csl.fx.trademarks;

				// when clicked, the listed trademark logos zoom in to show additional infos
                $('.trademarks a').click(function(evt){
                    evt.preventDefault();
                    $(this).parent('li').addClass('hovered');

                    // calculate the position of the infos and copy them to the overlay
                    that.startPos = { left: $(this).position().left, top: $(this).position().top };
                    var infos = '<div class="infos">'+$(this).parent('li').html()+'</div>';
                    $('#trademark_overlay').addClass('hovered').after(infos);

                    // animate the infos
                    $("#trademark_overlay").animate({opacity:.97}, that.duration);
                    $('.trademarks .infos div').css({opacity:0}).animate({opacity:1}, that.duration);
                    $(".trademarks .infos").css(that.startPos).animate(that.endPos, that.duration);

                });

				// when a logo is zoomed, another click closes the additional infos
                $('#trademark_overlay').click(function(evt){
                    evt.preventDefault();
                    $('.trademarks .infos div').animate({opacity:0}, that.duration);
                    $('.trademarks .infos').animate(that.startPos, that.duration, function(){ $(this).remove(); });
                    $('#trademark_overlay').animate({opacity:0}, that.duration, function(){ $(this).removeClass('hovered'); });
                });
            }


        }


    }, // end of object "fx"



    /**
     * microformats
     */
    microformats: {


        /**
         * start the whole microformats thing
         */
        initialise: function() {
            if ( $('.vcard').size() == 0 ) return;
            this.hCard.prepare();
        },



        /**
         * strip html tags from the given html code
         */
        stripTags: function(html) {
            if(html) return html.replace(/\<.+?\>/g, '');
            else return null;
        },



        /**
         * hCard
         * try to extract the vCard data from an hCard and save it as a *.vcf file
         */
        hCard: {


            /**
             * prepare the html, add an export link
             */
            prepare: function() {
                var name = csl.microformats.stripTags($('.vcard.exportable .fn').html());

                switch ( csl.docLang ) {
                    case 'de':
                        var exportTitle = 'Die Kontaktdaten von '+name+' als vCard exportieren'; break;
                    case 'en':
                        var exportTitle = 'Export the contact data of '+name+' as vCard'; break;
                }
                $('.vcard.exportable').css('position', 'relative').append('<a class="vCardExport" title="'+exportTitle+'"><span>vcard export</span></a>');

                $('.vCardExport').hover(
                    function() { $(this).css( 'cursor', 'pointer' ); },
                    function() { $(this).css( 'cursor', 'default' ); }
                );
                $('.vCardExport').click( function() {
                    csl.microformats.hCard.save( $(this).parents('.vcard') );
                });
            }, // end of function "prepare"




            /**
             * extract the data from the given html and save it as a vCard
             */
            save: function(html) {
                if (!html) return;

                var hCard = {
                    'given-name'       : csl.microformats.stripTags( jQuery.trim($(html).find('.given-name').html()) || '' ),
                    'family-name'      : csl.microformats.stripTags( jQuery.trim($(html).find('.family-name').html()) || '' ),
                    'organisation-name': csl.microformats.stripTags( $(html).find('.organisation-name').html() || '' ),
                    'title'            : csl.microformats.stripTags( $(html).find('.title').html() || '' ),
                    'street-address'   : csl.microformats.stripTags( $(html).find('.street-address').html() || '' ),
                    'country-name'     : csl.microformats.stripTags( $(html).find('.country-name').is('abbr') ? $(html).find('.country-name').attr('title') : $(html).find('.country-name').html() || '' ),
                    'postal-code'      : csl.microformats.stripTags( $(html).find('.postal-code').html() || '' ),
                    'locality'         : csl.microformats.stripTags( $(html).find('.locality').html() || '' ),
                    'email'            : csl.microformats.stripTags( $(html).find('.email').attr('href').replace( /mailto\:/g, '' ) || '' ),
                    'tel'              : csl.microformats.stripTags( $(html).find('.tel').find('.value').html() || '' ),
                    'fax'              : csl.microformats.stripTags( $(html).find('.fax').find('.value').html() || '' )
                };
                window.location = '/microformats_export.inc.php?os='+navigator.platform+'&'+jQuery.param(hCard);

            } // end of function "save"

        } // end of subobject "vCard"

    }, // end of subobject "microformats"




	observeTargetBlankLinks: function(){
		$('a.uoTargetBlank').attr('target', '_blank');
	},
	


	advertisingThemes: function(){

        $('.switchLinks a:not(.buttonDemografie)').click(function(evt){
            evt.preventDefault();
            document.getElementById('type').className = 'competition' + this.id;
			$('.switchLinks a').each(function(){
				$(this).removeClass('active' + this.id);
			});
			$(this).hasClass('active' + this.id) ? $(this).removeClass('active' + this.id) : $(this).addClass('active' + this.id);
        });


        $('.switchLinks input').change(function(evt){
            evt.preventDefault();
            if (this.checked) {
                if (this.id == 'siteBg') $('#site').addClass(this.id);
                else $('#adSwitch').addClass(this.id);
            } else {
                if (this.id == 'siteBg') $('#site').removeClass(this.id);
                else $('#adSwitch').removeClass(this.id);
            }
        });

	}
	

} // end of object "cls"




$(function() {
    csl.initialise();
});
