/**
 * JavaScript core
 *
 * @author  Peter Dobetsberger <p.dobetsberger@edelweiss72.de>
 *
 * Conventions:
 * Variables in camelCase
 * Classes in PascalCase
 * Function/Methods in camelCase
 */


// wechselt SPrachen
S.changeLanguage = function(url){
    location.href=url;
}


S.email = function(data){
    var pattern = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;

    if(data.match(pattern)){
        return true;
    }else{
        return false;
    }
}


// Suchfeldeingabe leer setzen
S.clearField = function (field,ignorestring) {
    if (document.getElementById(field).value==ignorestring) {
        document.getElementById(field).value='';
        document.getElementById(field).focus();
    }
}


/**
 * Fly-out navigation fÃ¼r den IE6
 */
S.hoverNavi = function() {
    //if(navigator.userAgent.match("MSIE 6.0")) {
    $(".moduleMainNav ul li").mouseover(
        function() {
            $(this).find("ul").show();
        });

    $(".moduleMainNav ul li").mouseout(
        function() {
            $(this).find("ul").hide();
        });
//}
}

S.createVcard = function(element){
    var vCard = $(element);

    //Binding fÃ¼r Print u. VCF
    vCard.bind("click", function(){
        vcf($(this));
        return false;
    });

    function vcf(elm){
        var daten = $(elm).parent().parent().children("p");
        var date = new Date();
        var vcf =   "BEGIN:VCARD"+"\n"+
        "FN:"+daten.eq(1).text()+"\n"+
        "ADR;POSTAL;WORK::"+daten.eq(0).text()+"\n"+
        "LABEL;POSTAL;WORK;ENCODING=QUOTED-PRINTABLE:"+daten.eq(0)+"\n"+
        "TEL;WORK;VOICE;MESG;PREF:"+daten.eq(3).text()+"\n"+
        //TEL;WORK;FAX:+49-6081-911170
        "EMAIL;Internet:"+daten.eq(4).text()+"\n"+
        //URL:http://www.riedborn-apotheke.de
        //UID:http://www.riedborn-apotheke.de
        "TZ:"+date.getTimezoneOffset()+"\n"+
        //"REV:"+date.getFullYear()+date.getMonth()+date.getDay()+"T"+date.getHours()+date.getMinutes()+date.getSeconds()+"\n"+
        "VERSION:2.1"+"\n"+
        "END:VCARD";




        $.post("/___easyred/easyred_project/templates/inc_functions/function_vcard.php", {
            data : vcf
        } ,function(data){
            document.location.href=data
        });
    }
}

S.printContact = function(element){
    var printer = $(element);

    //Binding fÃ¼r Print
    printer.bind("click", function(){
        print($(this));
        return false;
    });

    function print(elm){
        var content = elm.parent().parent().html();
        var winURL = "about:blank";
        var winName = elm.text();
        var ref = window.open('about:blank', 'winName', 'width=400, height=400, resizeable=yes, scrollable=yes, location=yes, menubar=yes, status=yes, dependent=no, left=150,top=150');
        $(window).ready(function(){
            ref.document.title = winName;
            ref.document.url = document.location.href;
            //content += '<input type="button" onclick="window.print();" value="'+winName+'" name="'+winName+'" />';
            ref.document.write(content);
            ref.document.close();
        });
        ref.print();
    }
}

S.sendVcf = function(selector){
    var $file = getLink(selector);
    
    /********/
    start($file);
    /********/
    
    function start(file){
        $(selector).click(function(e){
            var offset = $(selector).parent().parent().offset();
            var Top = e.pageY-100;
            ;
            var Left = e.pageX;
            var parent = $("body").append(writeHtml(file));
            setClose(parent.find(".jsClose"));
            parent.find(".gridLayer1").css({
                top : Top+"px", 
                left : Left-150+"px"
            });
            parent.find(".jsContent").html(makeForm(file));
            parent.find("form.jsVcfSend").submit(function(){
                var vars = $(this).serializeArray();
                if(S.email(vars[1].value)){
                    $.post($(this).attr("action"), vars, function(data){
         
                        if(data=='1'){
                            parent.find("form.jsVcfSend").html(js_contact_ok);
                        }else{
                            parent.find("form.jsVcfSend").html(js_contact_failed);
                        }
                        setTimeout(function(){
                            parent.find(".jsClose").click();
                        },3500)
                    });
                }else{
                    $(this).prepend("<div class='boxRow boxError'>"+js_invalid_email+"</div>");
                }
                return false;
            })
        });
    }
    
    function writeHtml(file){
        var output = '<div class="gridLayer1">'+
        '<div class="divL1Close clearfix">'+
        '<span class="jsClose" title="'+js_close+'">'+js_close+'</span>'+
        '</div>'+
        '<div class="divL1 jsContent"></div>'+
        '<div class="boxBottom">&nbsp;</div>'+
        '</div>';
        return output;
    }
    
    function makeForm(file){
        var id="email_"+ Math.round(Math.random(100) * 1000);
        var output =  '<div><form class="clearfix jsVcfSend" action="/___easyred/easyred_project/templates/inc_functions/function_vcf_mail.php?countrylanguage='+js_countrylanguage+' " method="post">'+
        '<input type="hidden" name="file" value="'+file+'" />'+
        '<div class="boxRow"><label>'+js_email_adress+'</label><input name="email" type="text" id="'+id+'" /></div>'+
        '<div class="boxRow"><input class="boxSubmit" type="submit" name="'+js_send_vcf+'" value="'+js_send_vcf+'" /></div>'
        '</form></div>';
        return output;
    }
    
    function setClose(selector){
        $(selector).click(function(){
            $(this).parent().parent().remove();
        })
    }
    
    function getLink(selector){
        return $(selector).attr("href");
    }
    
}

S.boeweMap = function(listRoot, optionChild){
    
    var liRoot = $(listRoot);
    var root = liRoot.parent().parent();
    var aanchors = liRoot.children("a");
    var abselects = liRoot.children(".boxSelect");
    //    var aoptions = $(optionChild+":enabled");
    var doptions = $(optionChild+":disabled");
    var vcf = $(".boxMail");
    var selecttext = $(optionChild).eq(0).parent().siblings("span").text();
    var adescriptions = liRoot.children(".boxDescription");
    var woptions = [];
    var wdescriptions = [];
    var wanchors = [];
    var rootHeight = root.height();
    $(optionChild+":disabled").attr("selected",true);

    //Baum hierarchisch durchsuchen und abspeichern
    for(var i = 0; i < liRoot.length; i++){
        woptions[i]= liRoot.eq(i).children(".boxSelect").children("select").children("option:enabled");
        wdescriptions[i]=liRoot.eq(i).children(".boxDescription");
        wanchors[i]=liRoot.eq(i).children("a");
    }

    //Bindings fÃ¼r a der LI
    for(var k = 0; k < wanchors.length ;k++){
        wanchors[k].bind("click",{},function(e){
            var sibl = $(this).siblings(".boxSelect");
            aanchors.removeClass("active");
            adescriptions.css("display","none");
            root.css("height",rootHeight + "px");
            sibl.children("span").text(selecttext);
            doptions.attr("selected", true);
            if(sibl.css("display") == "none"){
                abselects.css("display","none");
                sibl.css("display","block");
                $(this).addClass("active");
            }else{ 
                aanchors.removeClass("active");
                sibl.css("display","none");
            }
            return false;
        });
    }

    //Bindings fÃ¼r Options
    for(var j = 0; j < woptions.length; j++){
        woptions[j].parent().bind("change",{
            index : woptions[j],
            forindex : j
        },function(e){
            //alert("test");
            adescriptions.css("display","none");
            var newheight = (rootHeight / 3 + (wdescriptions[e.data.forindex].eq(e.data.index.index($(this).children("option:selected"))).height()));
            wdescriptions[e.data.forindex].eq(e.data.index.index($(this).children("option:selected"))).css("display","block");
            root.css("cssText","height: " + newheight + "px !important");
            var wtext = $(this).children("option:selected").text();
            $(this).parent().children("span").text(wtext);
        })

    //        woptions[j].bind("mouseover",function(e){
    //            var wtext = $(this).text();
    //            $(this).parent().parent().children("span").text(wtext);
    //        });
    }
}

/**
 * Erstellt einen Slider mit einer Timeline. Abstufung der Timeline erzeugt sich aus der Anzahl der option Felder
 * @param root: Rootelement durch css schreibweise
 * @param slider: Sliderelement
 * @param content: Content Container
 * @param cat: Element das den Inhalt der Beschriftung fÃ¼r die Timeline enthÃ¤lt
 * @param active: Bestimmt welches Element bei init aktiv sein soll / OPTIONAL sonst letztes
 */
S.sliderTime = function(root, slider, content, cat, active){
    var sliderRoot = $(root);
    var sliderself = $(slider);
    var slidercontent = $(content);
    //var opt = getOptions(sliderself);
    var contentchildren = slidercontent.children("div");
    var sWidth = getMetrics(sliderRoot);
    var start;
    if(typeof active== 'undefined'){
        var start = contentchildren.length-1;
    }else{
        var start = active - 1;
    }

    var timeLine = createTimeline(contentchildren, sliderRoot, start);
    var tWidth = createListStyle(sWidth, contentchildren.length, timeLine);
    var offset = timeLine.children("li.active").offset();
    var offset2 = sliderRoot.offset();
    var cordX = (offset.left + 13) - offset2.left;
    toggle(sWidth,cordX,contentchildren,timeLine, false);

    contentchildren.css("display","none");
    contentchildren.eq(start).css("display","block");


    //resetOption(opt);

    //Binding
    sliderself.bind("mousedown",function(e){
        $("body").bind("mousemove",function(e){
            var offset = sliderRoot.offset();
            var cordX = e.pageX - offset.left - (parseInt(sliderRoot.children("div").css("marginLeft"))) - 8;
            if(parseInt(cordX) >= 13 && parseInt(cordX) < (sWidth)){
                sliderself.css("left", cordX + "px");
            }
        });
    }).bind("mouseup",function(e){
        var offset = sliderRoot.offset();
        var cordX = e.pageX - offset.left - (parseInt(sliderRoot.children("div").css("marginLeft"))) - 8;
        toggle(sWidth,cordX,contentchildren,timeLine, true);
        $("body").unbind("mousemove");
    });

    timeLine.children("li").bind("click",function(e){
        var offset = $(this).offset();
        var offset2 = sliderRoot.offset();
        var cordX = (offset.left + 13) - offset2.left;
        toggle(sWidth, cordX, contentchildren, timeLine, true);
    });

    //Holt die Optionsfelder
    function getOptions(sib){
        var opt = sib.siblings("select").children("option");
        return opt;
    }

    //Erstellt den Zeitstrahl
    function createTimeline(con, root, active){
        var status = "";
        var output = "<ol class='clearfix'>";
        for(var i = 0; i < con.length; i++){
            status = "";
            if(active == i)
                status = " active";
            if(i==0){
                output += "<li class='boxFirst"+status+"'>"+con.eq(i).children(cat).text()+"</li>";
            }else{
                if(i != 0 && i == con.length-1){
                    output += "<li class='boxLast"+status+"'>"+con.eq(i).children(cat).text()+"</li>";
                }else{
                    output += "<li class='"+status+"'>"+con.eq(i).children(cat).text()+"</li>";
                }
            }
        }
        root.prepend(output);
        return root.children("ol");
    }

    //Erfasst die Abmessungen des Sliders
    function getMetrics(root){
        var sWidth = root.children("div").width();
        return sWidth;
    }

    //Erstellt den Style des Sliders
    function createListStyle(val1, val2, elm){
        var twidth = val1 / val2;
        elm.children("li").css("width", twidth + "px");
        return twidth;
    }

    //Wechselt den ausgewÃ¤hlten Optioneintrag/ Activestatus der Timeline
    function toggle(val1, val2, mult, list, anim){
        var t= (val2+17) * mult.length;
        var e = Math.floor(t / val1);
        e = (e < mult.length) ? e : mult.length -1;
        e = (e > 0 && e < mult.length) ? e : 0 ;
        var offset = list.children("li").eq(e).offset();
        var offset2 = sliderRoot.offset();
        var cordX = (offset.left - 17) - offset2.left + tWidth / 2;
        if(list.children("li").eq(e).hasClass("active")){
            if(anim){
                sliderself.animate({
                    left : cordX + "px"
                });
            }else{
                sliderself.css({
                    left : cordX + "px"
                });
            }
        }else{
            list.children("li").removeClass("active");
            list.children("li").eq(e).addClass("active");
            mult.attr("selected",false);
            mult.eq(e).attr("selected",true);
            if(anim){
                sliderself.animate({
                    left : cordX + "px"
                });
            }else{
                sliderself.css({
                    left : cordX + "px"
                });
            }
            viewContent(e);
        }
    }

    //Reset der Options
    function resetOption(elm){
        elm.eq(0).attr("selected",true);
    }

    //content ein/ausblenden
    function viewContent(num){
        contentchildren.css("display","none");
        contentchildren.eq(num).fadeIn(1000);
    }

}



/**
 * @Object
 * Template
 */
S.Template = {

    /**
     * Layer top-posotion-difference
     */
    contentLayerTopDif: -151,

    /**
     * Layer status-constants
     */
    contentLayerStatusOpen: 2,
    contentLayerStatusClosed: 1,
    contentLayerNotCreated: undefined,

    contentLayerStack: new Array(),


    /**
     * Creates an content-layer and saves it into the jsQuery-data object (opener)
     * and tranfers the html-content from an another element (contetn)
     *
     * @param   {String}   opener  - Id name from the opener tag
     * @param   {String}   content - Id from the module-content (content-transfering)
     * @param   {Number}   topDif  - Top-position difference
     * @returns {Boolean}
     */
    switchContentLayer: function(opener, content, topDif)
    {
        var $opener = $(opener);
        var $layer, $container, $content;
        
        switch ($opener.data('layerStatus')) {

            // --------------------------------
            // First click: Create new layer
            // --------------------------------
            case this.contentLayerNotCreated:

                $container = $('.gridCenter');
                $layer = this.createNewLayer();
                $content = $(content);
                $layer.find('.jsContent').html($content.html());

                var topDifPos = (topDif === undefined) ? this.contentLayerTopDif : this.contentLayerTopDif + topDif;
                $layer.css('top', parseInt($opener.offset().top + topDifPos)+'px');

                $container.append($layer);
                $content.remove();

                $layer.find('.jsClose').click(function(){
                    $layer.css('display', 'none');
                    $opener.data('layerStatus', S.Template.contentLayerStatusClosed);
                });

                $opener.data('layer', $layer);
                $opener.data('layerStatus', this.contentLayerStatusOpen);
                this.contentLayerStack.push($opener);
                break;

            // --------------------------------
            // Layer is closed: Open layer
            // --------------------------------
            case this.contentLayerStatusClosed:

                $layer = $opener.data('layer');
                $layer.css('display', 'block');
                
                var topDifPos = (topDif === undefined) ? this.contentLayerTopDif : this.contentLayerTopDif + topDif;
                $layer.css('top', parseInt($opener.offset().top + topDifPos)+'px');

                $opener.data('layerStatus', this.contentLayerStatusOpen);
                break;

            // --------------------------------
            // Layer is open: Close layer
            // --------------------------------
            case this.contentLayerStatusOpen:

                $layer = $opener.data('layer');
                $layer.css('display', 'none');

                $opener.data('layerStatus', this.contentLayerStatusClosed);
                break;

        }
        return false;
    },


    /**
* Creates an new html-element-node (layer) as an jQuery-object
*
* @returns {Object}  - jQuery
*/
    createNewLayer: function()
    {
        return $(
            '<div class="gridLayer1">'+
            '    <div class="divL1Close">'+
            '        <span class="jsClose" title="Schlie&szlig;en">Schlie&szlig;en</span>'+
            '    </div>'+
            '    <div class="divL1 jsContent"></div>'+
            '    <div class="boxBottom"></div>'+
            '</div>'
            );
    }

    

}


/**
* @class
* Gallery
*/
S.SLIDE_START = 1; //flag start slide show
S.SLIDE_PAUSE = 2; //pause start slide show
S.Gallery = function(pInstanceName, titles) 
{
    var instance = this;
    var instanceName;

    var $galleryNode = null;
    var $links = null;

    var $currentImage = null;
    var loadedImages = new Array();

    var $imageCont = null;
    var $imageAnim = null;
    var $imageTitle = null;
    var currentIndex = 0;

    var animDuration = 500;
    
    var $next = null;
    var $prev = null;
    var $playPause = null;
    
    var slideshowActive = false;
    var slideshowInterval = 2000;
    var slideshowTimeout;
    
    var controlTitles = {
        next:"",
        prev: "",
        startSlideshow: "",
        stopSlideshow: ""
    };
    
    


    // --------------------------------------------------------
    // Constructor --------------------------------------------
    // --------------------------------------------------------

    /**
* Conscrutor
*
* @param {String} pInstanceName   ~ Instance-Name
* @param {Object} titles - Title Attivures for Controls
*/
    function __construct(pInstanceName, titles)
    {
        if(titles !== undefined){
            controlTitles = titles;
        } 
        instanceName = pInstanceName;
        $galleryNode = $(pInstanceName);
        $links = $galleryNode.find("li");
        
        _loadImages();
        _createImageContainer();
        _registerEvents();
    }


    // --------------------------------------------------------
    // Public -------------------------------------------------
    // --------------------------------------------------------


    /**
* Shows the selected images by calling the private members
*
* @param   {Integer} index
* @param   {Boolean} animation     ~ with or without animation
* @returns {object}                ~ instance
*/
    this.show = function(index, animation)
    {
        S.strict([Number], [index]);

        index--;
        currentIndex = index;
        $currentImage = $galleryNode.find('li img:eq('+index+')');
        //if index does not exists, show first image
        if($currentImage.length === 0){
            index = 0;
        }

        if (animation !== undefined && animation === true) {
            _anim();
        }
        _show(index);
        return instance;
    }


    /**
* Set duration from animation
*
* @param   {Integer} seconds   ~ time in Seconds
* @returns {object}            ~ instance
*/
    this.duration = function(seconds)
    {
        S.strict([Number], [seconds]);
        animDuration = seconds*1000;

        return instance;
    }
    
    /**
     * Starts the silde show
     * @param {Integer} interval : time between siwtches in seconds
     * @param {Integer} action : S.SLIDE_START start die slideshow
     *                           S.SLIDE_PAUSE pauses the slide show
     */
    this.slideshow = function(interval, action){
        
        slideshowInterval = interval*1000;
        $playPause.show();
        if(action === S.SLIDE_START){
            slideshowActive = true;
            $playPause.addClass("playing");
            $playPause.attr("title", controlTitles.stopSlideshow);
            setTimeout(
                function(){
                    if(slideshowActive){
                        _slideStart();
                    }
                    
                },
                slideshowInterval);
        }
        return instance;
    }

    // --------------------------------------------------------
    // Private ------------------------------------------------
    // --------------------------------------------------------
    /**
 * Recursive functon: slides to next images while slideshowActive is true
 */
    function _slideNext(){
    
        _next();
        clearTimeout(slideshowTimeout);
        slideshowTimeout = setTimeout(
            function(){
                if(slideshowActive){ _slideNext();}
            },slideshowInterval);
    }

    function _slideStart(){
        slideshowActive = true;
        $playPause.addClass("playing");
        $playPause.attr("title", controlTitles.stopSlideshow);
        _slideNext();
    }

    /**
 * Stops the slide show
 */
    function _slideStop(){
        slideshowActive = false;
       $playPause.removeClass("playing");
       $playPause.attr("title", controlTitles.startSlideshow);
    }

    /**
* Show the next image. Skips to the first image once the last image is reached
*/
    function _next(){
        var index = currentIndex+1;
        if(index === loadedImages.length){
            index = 0;
        }
        instance.show(index+1, true); //show index is 1 based
    }
    /**
* Show the previous image. Skips to last image once the first image is reched
*/
    function _prev(){
        var index = currentIndex-1;
        if(index < 0){
            index = loadedImages.length-1;
        }
        instance.show(index+1, true); //show index is 1 based
    }


    /**
* Show image
*
* @param {Integer} index
*/
    function _show(index)
    {
        //$imageCont.attr('src', $currentImage.attr('alt'));
        $imageCont.attr('src', loadedImages[index].src);
        $imageTitle.text($currentImage.attr('title'));

        $links.removeClass('active');
        $links.eq(index).addClass('active');
        _setVerticalImageClass();
        currentIndex = index;
    }


    /**
* Animate
*
*/
    function _anim()
    {
        $imageAnim.attr('src', $imageCont.attr('src'));
        $imageAnim.css({
            display: 'block',
            opacity: 1
        });
        $imageAnim.animate({
            opacity: 0
        }, animDuration, function() {
            $imageAnim.css('display', 'none');
        });
    }


    /**
* Creating the click-events
*
*/
    function _registerEvents()
    {
        var $imgLinks = $links.find("img");
        $imgLinks.each(function(){
            var index = $imgLinks.index(this);
            index++;
            $(this).focus(function(){
                this.blur();
            });
            $(this).click(function(){
                _slideStop();
                return instance.show(index, true);
            });
        });
        
        $next.click(function(){
            _slideStop();
            _next();
        });
        
        $prev.click(function(){
            _slideStop();
            _prev();
        });
        
        $playPause.click(function(){
            if(slideshowActive){
                _slideStop();
            }else{
                _slideStart();
            }
        });
    }


    /**
* Creating the zoom-image container
*
*/
    function _createImageContainer()
    {
        $('<div class="boxImageC">' +
            '    <img src="" class="jsImage" />' +
            '    <img src="" class="jsAnimation" />' +
            '    <p class="jsTitle boxDescription"></p>' +
            '    <div class="boxControls">' +
            '       <a href="javascript:void(0)" class="boxNext" title="'+controlTitles.next+'"></a>' +
            '       <a href="javascript:void(0)" class="boxPrev" title="'+controlTitles.prev+'"></a>' +
            '       <a href="javascript:void(0)" class="boxPlayPause" title="'+controlTitles.startSlideshow+'"></a>' +
            '    </div>' +
            '</div>'
            ).prependTo($galleryNode);

        $imageCont = $galleryNode.find('.jsImage');
        $imageAnim = $galleryNode.find('.jsAnimation');
        $imageAnim.attr('src', loadedImages[currentIndex].src);
        $imageAnim.css('left', 0);
        $imageTitle = $galleryNode.find('.jsTitle');
        $next = $galleryNode.find('.boxNext');
        $prev = $galleryNode.find('.boxPrev');
        //_setVerticalPos($next);
        //_setVerticalPos($prev);
        $playPause = $galleryNode.find('.boxPlayPause');
    }
    
    /**
     * Set the vertical position of elem to middle
                                      
     * @param (jQueryObject) $elem : Element that is to be positioned
     */
    
    function _setVerticalPos($elem){
        
        var pos = 338/2 - 118/2;
        $elem.css("top", pos+"px");
    }


/**
* Loads all images from server
*
*/
    function _loadImages()
    {
        var $images = $links.find("span");
        var image;
        for (var i=0; i<$images.size(); i++) {
            image = new Image();
            image.src = $images.eq(i).text();
            loadedImages.push(image);
        }
    }

    /**
* Loads all images from server
*/
    function _setVerticalImageClass()
    {
        var $images = $links.find("img");
        for (var i=0; i<$images.size(); i++) {
            var isHoriz = ($images.get(i).offsetWidth < $images.get(i).offsetHeight) ? true : false;

            if (isHoriz) {
                $links.eq(i).addClass('boxFormat');
            }
        }
    }


    // Init class
    window.S.Data.set(pInstanceName, instance);
    __construct(pInstanceName, titles);

}

/**
 * @class Handles visibility of nes items on the news index page according to their type an year
 **/
S.NewsSelect = function(newsElemSelector, selectElemSelector,typeTextMapping,emptyTextSelector,zebra)
{
    var self = this;
    var allText = typeTextMapping[0];
    var allValue = "0";
    var showAllOnLoad = false;
    if(typeof(zebra) === "undefined" || zebra === null){
        zebra = false;
    }
    
    var YEAR = 1;
    var TYPE = 2;
    
    var selectedType = "";
    var selectedYear = "";
    var $emptyText = $(emptyTextSelector);
    var $newsElems = $(newsElemSelector);
    var $selets  = $(selectElemSelector);
    var $typeSelect = $selets.eq(0);
    var $yearSelect = $selets.eq(1);
    
    this.init = function(all){
        if(typeof(all) === "undefined" || all === null){
            all = false;
        }
        showAllOnLoad = all;
        var types = getData($newsElems, TYPE);
        var years = getData($newsElems, YEAR);
        if(showAllOnLoad != all){
            selectedType=types[0];
            selectedYear=years[0];
        }else{
            selectedType="0";
            selectedYear="0";
        }
        var optionsType = getOptions(types, TYPE);
        var optionsYear = getOptions(years, YEAR);
        $typeSelect.html(optionsType);
        $yearSelect.html(optionsYear);
        
        $typeSelect.change(function(){
            select(selectedYear, $(this).val());
        });
        $yearSelect.change(function(){
            select($(this).val(), selectedType);
        });
        $(selectElemSelector).show();
        select(selectedYear, selectedType);
    }
    
    var getOptions = function(values, op){
        var ret ="";
        if(showAllOnLoad){
            ret += "<option value='"+allValue+"'>"+allText+"</option>";
        }
        for(var i =0; i<values.length; i++){
            if(op===TYPE){
                ret+= buildOptionType(values[i]);
            }
            else if(op===YEAR){
                ret+= buildOptionYear(values[i]);
            }
        }
        return ret;
    }
    
    var buildOptionYear = function(year){
        return '<option value="'+year+'">'+year+'</option>';
    }
    
    var buildOptionType = function(type){
        return '<option value="'+type+'">'+typeTextMapping[type]+'</option>';
    }
	
    /**
    * Selects year
    */
    var select = function(year, type)
    {
        var elemYear, elemType, $e;
        var counter  =0;
        var visible = false;
        $emptyText.hide();
        selectedYear =year;
        selectedType =type;
        $newsElems.each(
            function(index, elem)
            {
                $e = $(elem);
                elemType = getType(elem);
                elemYear = getYear(elem);
                if((year === elemYear || year === allValue)
                    && (type===elemType || type===allValue)){
                    $e.show();
                    counter++;
                    visible = true;
                }else{
                    $e.hide();
                    visible = false;
                }
                if(zebra !== false && visible)
                {
                    if(counter%2 === 1){
                        $e.addClass(zebra.oddClass);
                    }
                    else{
                        $e.addClass(zebra.evenClass);
                    }
                }
               
            });
        if(counter ===0){
            $emptyText.show();
        }
    }
	
    var getData = function($elems, op){
        var ret=[];
        $elems.each(function(i,e){
            var val = "";
            if(op===TYPE){
                val = getType(e);
            }
            else if(op===YEAR){
                val = getYear(e);
            }   
            if($.inArray(val, ret) === -1){
                ret.push(val);
            }
            
        });
        return ret;
    }
    
    var getType = function(elem){
        var split = elem.id.split("_");
        return split[split.length-1];
    }
    
    var getYear = function(elem){ 
        var split = elem.id.split("_");
        var dateSplit = split[1].split("-");
        return dateSplit[0];
    }  
 
};

/**
* Class used for Zebra
*/
S.Zebra = function(evenClassName, oddClassName)
{
    this.evenClass = evenClassName;
    this.oddClass = oddClassName;
}

/**
 * @param gallery, css class der Gallery
 */
S.imageGallery = function(gallery, duration) {
    
    
    //init
    var _$gallery = $(gallery);
    var time;
    if(duration){
        var _$duration = duration;
    }else{
        var _$duration = 3500;
    }

    //Anzahl Bilder => Anzahl Beschreibungen
    var _$images = _$gallery.children("img");
    var imageAnzahl = _$images.length;

    //Pfade speichern
    var imgPath = [];
    for(var i = 0; i < imageAnzahl; i++){
        imgPath.push(_$images.eq(i).attr("src"));
    }
    
    var time;
    
    reset_gallery();


    function reset_gallery(){
        for(var i = 0; i < imageAnzahl; i++){
            if(i == 0 || i == 1){
                _$images.eq(i).css("position","absolute").css("zIndex",2-i);

            }else{
                _$images.eq(i).css("position","absolute").hide();
            }
        }
    }


    /**
     * @param index, position des Bildes/Beschreibung die aktiv werden soll
     * @param that, aktuelles Element (parent)
     */
    this.toggle_image = function(index, that){
        toggle_image(index, that);
    }
    
    
    function toggle_image(index, that){
        //img tauschen
        if(!that.children("li").eq(index).hasClass("active")){
            _$images.eq(0).stop(true, true);
            _$images.eq(1).attr("src", imgPath[index]);
            _$images.eq(0).fadeOut(500,function(){
                $(this).attr("src", imgPath[index]);
            }).fadeIn(500);
        
            //marker setzen
            that.children("li").removeClass("active");
            that.children("li").eq(index).addClass("active");
        }
    }


    this.generate_controller = function(){
        if(imageAnzahl > 1){
            var id = "img_" + Math.round((Math.random() * 1000));
            var html = "<ul id='"+id+"'>";
            for(var j = 0; j < imageAnzahl; j++){
                if(j == 0){
                    html += "<li class='active'><span>"+(j+1)+"</span></li>";
                }else{
                    html += "<li><span>"+(j+1)+"</span></li>";
                }
            }
            html += "</ul>";
            _$gallery.append(html);            

            //append mouseover
            var _$buttons = $("#"+id).children("li");
            for(var k = 0; k < imageAnzahl; k++){
                _$buttons.eq(k).bind('mouseover',{
                    pos : k
                },function(event){
                    toggle_image(event.data.pos, $(this).parent());
                    clearTimeout(time);
                    start_gallery();
                });
            }
        }
    }
    
    
    function start_gallery(){        
        time = setTimeout(function(){
            var lis = _$gallery.children("ul").children("li");
            var lisA = _$gallery.children("ul").children("li.active");
            var index = lis.index(lisA);
            if(index == lis.length - 1){
                toggle_image(0, _$gallery.children("ul"));
            }else{
                toggle_image(index+1, _$gallery.children("ul"));
            }            
            clearTimeout(time);
            start_gallery();
        }, _$duration);
    }
    
    
    this.start_gallery = function(){
        if(imageAnzahl > 1){
            start_gallery();
        //            _$gallery.bind("mouseover", function(){
        //                clearTimeout(time);
        //            }).bind("mouseout", function(){
        //                start_gallery();
        //            });
        }
    }
}

S.replaceSelect = function(selectorSelect){

    var $select = $(selectorSelect);

    $(document).ready(function(){
        $select.each(function(index){
            var select = $(this);
            var tmp = select.parent();
            var pos = select.offset();
            var parPos = tmp.offset();
            var left = pos.left - parPos.left;
            select.after('<div class="jsSelect">&nbsp;</div>');
            var div = tmp.find(".jsSelect");
            
            if(div.length > 1){
                div = div.eq(index);
            }else{
            //
            }
            
            if(select.css("position") != "absolute"){
                select.css( {
                    opacity : 0,
                    filter:"alpha(opacity=0)",
                    position : "relative", 
                    zIndex : 1
                });
            }else{
                select.css( {
                    opacity : 0,
                    filter:"alpha(opacity=0)",
                    zIndex : 1
                });
            }

            var selected = select.find("option:selected");
            if(selected.length == 0){
                div.text(select.find("option").eq(0).text());
            }else{
                div.text(selected.eq(0).text());
            }
            
            tmp.css({
                position : "relative"
            });
            
            var top = parseInt(pos.top) - parseInt(parPos.top);
        
            //Berechnungen;
            var bgPos = 0;
            if(parseInt(select.css("width")) < 200){
                bgPos = -100;
            }
            if(parseInt(select.css("width")) < 140){
                bgPos = 0;
            }
            if(parseInt(select.css("width")) > 200){
                bgPos = -200;
            }
            
            var width = parseInt(select.width());
        
            div.css({
                position : "absolute", 
                top : top + "px" , 
                //left : left+"px", 
                //right : select.css("right"), 
                bottom : select.css("bottom"),
                width : width+"px",
                backgroundPosition : "0px "+bgPos+"px",
                zIndex : 0
            });
            
            var calcOffset = parseInt(tmp.css("width")) - (left + parseInt(div.outerWidth()));
            if(calcOffset < 0)
                left += calcOffset;
            
            div.css({
                left : left+"px"
            });
                            
            select.bind("change", function(){
                div.text(select.find("option:selected").text());
            });
        });
    });
}
