var drt = {
    test: false,
    title: document.title
};


if (drt.test) {
    document.title = "DRT – lade Dateien…";
}

if (google){google.load("feeds", "1");}

$(function() {
    if (drt.test) {
        document.title = "DRT – Initialisierung…";
    }
    
    drt.print.init();
    drt.teasers.init();
    drt.filter_ov.init();
    drt.search.init();
    drt.collapsable.init();
    drt.tunnel.init();
    drt.slideshow.init();
    drt.playlist.init();
    drt.forms.init();
    
    
    $(".tabthis").each(function(){
        var id = "#"+this.id;
        $(this).find('.tabs').tabs(id+' .pane', {effect: 'fade', fadeOutSpeed: 400});
    });
    if(FB){
        FB.init({
            appId : '202533913115599',
            status : true, // check login status
            cookie : true, // enable cookies to allow the server to access the session
            xfbml : true // parse XFBML
        }); 
    }
    document.title = drt.title;
});


drt.forms = {
    init : function(){
        $.tools.validator.localize("de", {
            '*'      : 'Dieses Feld enthält einen ungültigen Wert.',
            ':email'    : 'Dieses Feld muss eine gültige E-Mail-Adresse enthalten.',
            '[required]'  : 'Dieses Feld darf nicht leer sein.'
        });
        $("#newsletterForm").validator({
            lang: 'de',
            position: 'bottom left'
        }).submit(function(e) {
            var form = $(this);
            // client-side validation passed
            if (!e.isDefaultPrevented()) {
                // submit the data to the server with AJAX
                xajax_ajaxDispatcher('form', 'submit', 'newsletter', [xajax.getFormValues('newsletterForm')]);
                // prevent default form submission logic
                e.preventDefault();
            }
        });
        $("#contactForm").validator({
            lang: 'de',
            position: 'bottom left'
        }).submit(function(e) {
            var form = $(this);
            // client-side validation passed
            if (!e.isDefaultPrevented()) {
                // submit the data to the server with AJAX
                xajax_ajaxDispatcher('form', 'submit', 'contact', [xajax.getFormValues('contactForm')]);
                // prevent default form submission logic
                e.preventDefault();
            }
        });
    }
};

drt.print = {
    init : function(){
        if (location.search ==='?preview=print'){
            $('link').each(function(){
                if ($(this).attr('media') === 'print'){
                    $(this).attr('media','all');
                }
            });
            $('article .actions .print').click(function(ev){
                ev.preventDefault();
                window.print();
            });
        } else{
            $('article .actions .print').click(function(ev){
                ev.preventDefault();
                var purl = location.href + "?preview=print";
                var pw = window.open(purl, "", "width=800,height=600,left=100,top=100,scrollbars=yes,toolbar=no,menubar=no");
                pw.focus();
            });
        }
    }
};


drt.slideshow = {
    init : function(){
        $(".slideshow").each(function(){
            // initialize paging count
            $(this).find(".paging .count").html("1 / "+$(this).find(".image").length);
            
            // set widths
            var col_width = $(this).width();
            $(this).width(col_width);
            $(this).find("li").each(function(index) {
                $(this).width(col_width);
            });
            
            // set heights
            var img_height = Math.max(20,$(this).find("img").height());
            var txt_height= 0;
            $(this).find("section").each(function(){
                if($(this).height()>txt_height){
                    txt_height = $(this).height();
                }
            });
            $(this).height(img_height+txt_height+20);
            $(this).find(".paging").css("top",img_height-38);
            
            
            
            // initialize scrolling
            var scroll_options = {};
            if(window.mode !=='edit'){
                scroll_options.circular = true;
            }
            if($(this).hasClass('autoscroll')){
                $(this).scrollable(scroll_options).autoscroll({ interval: 2000, autopause: false });
            } else {
                $(this).scrollable(scroll_options);
            }
            this.api = $(this).data("scrollable");
            
            // stop autoscroll on arrowclick
            this.api.getNaviButtons().click(function(){
                var s = $(this).closest('.slideshow')[0];
                if($(s).hasClass('autoscroll')){
                    s.api.stop();
                }
            });
            
            //update count on sliding
            this.api.onSeek(function() {
                var s = (this.getIndex()+1) + " / " + this.getSize();
                this.getRoot().find(".paging .count").html(s);
            });
        });
    }
};

drt.playlist = {
    init : function(){
        $('.playlist-teasers').each(function(i,el){
            var firstitem = $(el).find('.thumb')[0];
            if(firstitem !== undefined){
                var srchP = new RegExp(firstitem.id, "g");
                var player = $(el).find('.videoplayer')[0];
                var embedHTML = player.innerHTML.replace(srchP,"[VIDEOID]");
                //embedHTML = embedHTML.replace(/autoplay=./,"autoplay=1");
                $(el).find('.thumb').each(function(i,thumb){
                    thumb.player = player;
                    $(thumb).click(function(){
                        this.player.innerHTML = embedHTML.replace(/\[VIDEOID\]/g,this.id);
                        //console.log(embedHTML)
                    });
                });
            }
        });
    }
};

drt.teasers = {
    init : function(){
        $('#navi-teaser li, .teaser').each(function(i,el){
            // make container act as its link
            if(window.mode !=='edit'){
                $(this).click(function(){
                    location.href = $(this).find('a')[0].href;
                });
            }
        });
    }
};

drt.collapsable = {
    init : function(){
        $('dl.collapsable').each(function(ii){
            var contents = $(this).find('dd');
            $(this).find('dt').each(function(i){
                var t = this;
                contents[i].t = t;
                this.c = contents[i];
                this.toggle = function(){
                    $(this).toggleClass('active');
                    $(contents[i]).slideToggle(900, function() {
                        if(this.t.listener) {
                            this.t.listener({
                                action:'toggle',
                                result:$(this.t).hasClass('active')
                            });
                        }
                    });
                };
                $(this).click(function(){
                    this.toggle();
                });
            });
            $(this).find('.btn-collapse').click(function(){
                this.parentNode.t.toggle();
            });
        });
    }
};

drt.filter_ov = {
    init : function(){
        if($('#navi-topicoverview')){
            $('#navi-topicoverview a').each(function(){
                var type = "icon-"+this.className.slice(5);
                var count = $('.list-teasers .'+type).length;
                if (count > 0 || type === 'icon-all' ){
                    $(this).attr('title', count + ' Einträge gefunden');
                    $(this).click(function(){
                        $('#navi-topicoverview li').each(function(){
                            $(this).removeClass('active');
                        });
                        $(this).parent().addClass('active');
                        $('.list-teasers').addClass('anim');
                        if(this.className === 'show-all'){
                            $('.list-teasers .teaser').fadeIn('fast',function(){
                                $('.list-teasers').removeClass('anim');
                            });
                        } else {
                            var type = "icon-"+this.className.slice(5);
                            $('.list-teasers .teaser').hide();
                            $('.list-teasers .'+type).parents('.teaser').fadeIn('fast',function(){
                                $('.list-teasers').removeClass('anim');
                            });
                        }
                        return false;
                    });
                } else {
                    $(this).addClass('disabled');
                    $(this).click(function(){return false;});
                }
            });
        }
    }
};

drt.search = {
    init : function(){
        $('#searchbox').focus(function(){
            if ($(this).hasClass('empty')){
                this.defaultvalue = this.value;
                $(this).val('');
                $(this).removeClass('empty');
            }
        });
        $('#searchbox').blur(function(){
            if ($(this).val() === ''){
                $(this).val(this.defaultvalue);
                $(this).addClass('empty');
            }
        });
        $('#searchbutton').click(function(){
            if ($('#searchbox').hasClass('empty')){
                alert("nope");
                return false;
            } else {
                $('#search').submit();
            }
        });
    }
};

drt.create = function (a) {
    var el = null;
    if (a.nodeName) {
        el = document.createElement(a.nodeName);
        if (a.textNode) {
            var tn = document.createTextNode(a.textNode);
            el.appendChild(tn);
        }
        if (a.id) { el.id = a.id; }
        if (a.className) { el.className = a.className; }
        if (a.title) { el.title = a.title; }
        if (a.name) { el.name = a.name; }
        if (a.src) { el.src = a.src; }
        if (a.href) { el.href = a.href; }
        if (a.style) { el.style = a.style; }
        if (a.onclick) { el.onclick = a.onclick; }
        if (a.onmouseover) { el.onmouseover = a.onmouseover; }
        if (a.onmouseout) { el.onmouseout = a.onmouseout; }
        if (a.parentNode) { a.parentNode.appendChild(el); }
        if (a.target) { el.target = a.target; }
        if (a.callback) {
            $(el).load(function(){a.callback(el);});
        }
    }
    return el;
};

drt.tunnel = {
    cookie: $.cookie("tunnel"),
    init : function(){
        this.loaded = false;
        
        //console.log(this.cookie)
        if($.cookie("tunnel") !== 'false'){
            this.load();
            $('#tunnel .collapsable dt')[0].toggle();
            var t1 = setTimeout(function(){
                if($.cookie("tunnel") !== 'false'){
                    $('#tunnel .collapsable dt')[0].toggle();
                }
            },5000);
        }
        $('#tunnel .collapsable dt')[0].listener = function(a){
            $.cookie('tunnel', a.result, { expires: 1 });
            if(a.result && !drt.tunnel.loaded){
                drt.tunnel.load();
            }
            
        };
    },
    load : function(){
        this.loaded = true;
        
    ///// FB like
      
        // $('#fb-like')[0].href='http://www.facebook.com/marktwirtschaft';
        // $('#fb-facepile')[0].href='http://www.facebook.com/marktwirtschaft';
        
                
    ///// FB feed
        $('#feed-facebook').addClass('loading');
        this.getFeed({
            url : 'https://www.facebook.com/feeds/page.php?format=atom10&id=121678260974',
            callback : function(result){
                if (!result.error) {
                    var entry = result.feed.entries[0];
                    var txt = entry.content.replace(/<br>/g,". ");
                    $('#feed-facebook')[0].innerHTML = txt;
                    $('#feed-facebook').removeClass('loading');
                }
            }
        });
    ///// twitter feed
        drt.create({
            nodeName : 'DIV',
            className: 'loading',
            parentNode : $('#feed-twitter')[0]
        });
        var x = new TWTR.Widget({
              id: 'feed-twitter',
              version: 2,
              type: 'profile',
              rpp: 2,
              interval: 5000,
              width: 180,
              height: 300,
              theme: {
                    shell: {
                        background: 'transparent',
                        color: '#4c4c4c'
                },
                tweets: {
                    background: 'transparent',
                    color: '#4c4c4c',
                    links: '#3B5998'
                }
              },
              features: {
                    scrollbar: false,
                    loop: true,
                    live: false,
                    hashtags: true,
                    timestamp: true,
                    avatars: true,
                    behavior: 'default'
              }
        }).render().setUser('insm').start();
//                console.log('t_ok',x)
        
    ///// youtube feed
        $('#feed-youtube').addClass('loading');
        this.getFeed({
            url : 'http://www.youtube.com/rss/user/INSMBerlin/videos.rss',
            callback : function(result){
                var i = 0;
                if (!result.error) {
                    var hDiv = document.createElement('DIV');
                    var hHtml = '';
                    for(i = 0; i < 2; i++){
                        var e = result.feed.entries[i];
                        hDiv.innerHTML += e.content;
                    }
                    $(hDiv).find('a img').each(function(){
                        hHtml += $(this).parent().parent().html();
                    });
                    $('#feed-youtube')[0].innerHTML = hHtml;
                    $('#feed-youtube').removeClass('loading');
                }
            }
        });
    ///// INSM feed
        this.getFeed({
            url : 'http://www.insm.de/rss/?generatorName=templateContent&category=content&subCategory=article&siteRoot=/insm',
            callback : function(result){
                var i = 0;
                if (!result.error) {
                    for(i = 0; i < 3; i++){
                        var entry = result.feed.entries[i];
                        var txt = "<h5><a href='"+entry.link+"'>"+entry.title+"</a></h5>";
                        txt += "<p>"+entry.contentSnippet+"</p>";
                        $('#feed-insm')[0].innerHTML += txt;
                    }
                }
            }
        });
    ///// ecoblog feed
        this.getFeed({
            url : 'http://www.insm-oekonomenblog.de/feed/',
            callback : function(result){
                var i = 0;
                if (!result.error) {
                    for(i = 0; i < 3; i++){
                        var entry = result.feed.entries[i];
                        //console.log(entry);
                        var txt = "<h5><a href='"+entry.link+"'>"+entry.title+"</a></h5>";
                        txt += "<p>"+entry.contentSnippet+"</p>";
                        $('#feed-ecoblog')[0].innerHTML += txt;
                    }
                    $('#feed-ecoblog a').attr('target','_blank'); //has to be fixed.
                }
            }
        });
        
    },
    
    getFeed :  function(p){
        var feed = new google.feeds.Feed(p.url);
        feed.load(p.callback);
    }
};

