﻿/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
    var    token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };
    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;
        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }
        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) return ''; //throw SyntaxError("invalid date");
        mask = String(dF.masks[mask] || mask || dF.masks["default"]);
        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }
        var    _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };
        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();
// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa",
        "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"
    ],
    monthNames: [
        "Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez",
        "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"
    ]
};
// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};
// Nutzung: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
    log.history = log.history || [];   // store logs to an array for reference
    log.history.push(arguments);
    if(this.console){
        console.log( Array.prototype.slice.call(arguments) );
    }
};
/**
    Custom fadeIn - fixes IE display bug
*/
(function($) {
    $.fn.customFadeIn = function(speed, callback) {
        $(this).fadeIn(speed, function() {
            if(!$.support.opacity)
                $(this).get(0).style.removeAttribute('filter');
            if(callback != undefined)
                callback();
        });
    };
    $.fn.customFadeOut = function(speed, callback) {
        $(this).fadeOut(speed, function() {
            if(!$.support.opacity)
                $(this).get(0).style.removeAttribute('filter');
            if(callback != undefined)
                callback();
        });
    };
    $.fn.customFadeTo = function(speed,to,callback) {
        return this.animate({opacity: to}, speed, function() {
            if (to == 1 && jQuery.browser.msie)
                this.style.removeAttribute('filter');
            if (jQuery.isFunction(callback))
                callback();
        });
    };
})(jQuery);
function fl_registerTabs() {
    $('.fl_tab_bar .fl_tab_item').live('click', function() {
        // Dehighlight all tabs
        $(this).siblings().removeClass('fl_tab_item_hi');
        // Highlight tab
        $(this).addClass('fl_tab_item_hi');
        // Get position of tab
        var pos_tab = $(this).prevAll().length;
        
        // Hide all content boxes
        $(this).parents('.fl_tab_container_frame').find('.fl_tab_container').removeClass('fl_show').hide();
        // Show content box at position pos_tab
        $(this).parents('.fl_tab_container_frame').find('.fl_tab_container:eq(' + pos_tab + ')').addClass('fl_show').customFadeIn(300);
        
        /** Use only in tabs with feed */
        var count = $(this).parents('.fl_feed_container_frame').find('.fl_feed_item_hi a').html();
        if (count > 0 && count != null) {
            $(this).parents('.fl_tab_container_frame').find('.fl_tab_container:eq(' + pos_tab + ') .fl_item:lt(' + count + ')').show();
        }
    })
}
function fl_registerFeedDefault(count) {
    $('.fl_feed_container_frame').find('.fl_item:lt(' + count + ')').customFadeIn(300);
}
function fl_registerFeed() {
    
    $('.fl_feed_bar .fl_feed_item').live('click', function() {
        // Dehighlight all tabs
        $(this).siblings().removeClass('fl_feed_item_hi');
        var count = $(this).find('a').html();
        // Highlight tab
        $(this).addClass('fl_feed_item_hi');
        // Get position of tab
        var pos_tab = $(this).prevAll().length;
        
        // Hide all content entries
        $(this).parents('.fl_feed_container_frame').find('.fl_item').hide();
        if ($(this).parents('.fl_tab_container_frame').length > 0) {
            $(this).parents('.fl_feed_container_frame').find('.fl_show .fl_item:lt(' + count + ')').customFadeIn(300);
        } else {
            $(this).parents('.fl_feed_container_frame').find('.fl_item:lt(' + count + ')').customFadeIn(300);
        }
    })
}
function fl_resetBoxTabs(box_id) {
    var tabs = $(box_id).find('.fl_feed');
    // Dehighlight all tabs
    tabs.children().removeClass('fl_feed_item_hi');
    // Highlight tab
    tabs.children().eq(0).addClass('fl_feed_item_hi');
}
function fl_showPagingControls(box_id, items) {
    // Hide paging controls if not enough entries in list
    if (items > 0) {
        var count_buttons = Math.ceil(items / 3);
        $(box_id).find('.fl_feed_bar ul li').removeClass('hidden');
        
        if (count_buttons > 4)
            count_buttons = 4;
            
        $(box_id).find('.fl_feed_bar ul li:gt(' + (count_buttons - 1) + ')').addClass('hidden');
    } else {
        $(box_id).find('.fl_feed_bar ul li').addClass('hidden');
    }
}
/**
    Accordion
*/
function fl_registerAccordion(id) {
    if ($(id).length > 0) {
    $(id).accordion({
        autoHeight: false,
        navigation: true
    });
    }
}
/**
    Autocompleter
*/
$(function() {
    function split( val ) {
        return val.split( /\s+/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }
    $( "#inputFieldID" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                // Auf Testserver muss Proxy verwendet werden, 
                // auf Livesystem kann auch words.jsp direkt verwenet werden.
                $.getJSON( "autocompleter_proxy.php", {
                    q: extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( " " );                
                return false;
            }
        });
});
/**
    FadeIn
*/
function fl_registerToggleContent(id) {
    if ($(id).length > 0) {
        $(id + ' .fl_head').click(function() {
            $(this).addClass("fl_active");
            $(this).parent().find('.fl_container').hide();
            $(this).parent().find('.fl_head').not($(this)).removeClass("fl_active");
            $(this).next().customFadeIn(300);
            return false;
        })
    }
}
/**
    Colorchange searchbox
*/
function fl_registerToggleInputField(id, text) {
    if ($(id).val().length < 1) {
        $(id).val(text);
        $(id).click(function() {
            if ($(this).val() == text)
                $(this).val('');
            $(this).css('color', '#5A5B5F');
        });
    } else {
        $(id).css('color', '#5A5B5F');
    }
}
/** dimming screen */
function fl_dimMainblockArea(value) {
    if (value) {
        $('.fl_dim_layer').css('filter', 'alpha(opacity=80)');
        $('.fl_dim_layer').show();
    } else {
        $('.fl_dim_layer').hide();
    }
}
/* close box button */
function fl_registerCloseBox() {
    $('.fl_c').live('click', function(){
        $(this).parents('.fl_box').addClass('hidden');
        fl_save_all_boxstates();
    });
}
/* show/hide boxes */
function fl_registerBoxSwitches() {
    // Register toggle event
    $('ul.fl_checkboxlist li input').live('click',function(){
        var box_id = $(this).attr('value');
        $("#mag-" + box_id).toggleClass('hidden');
    });
}
/* helper function */
function fl_getValue() {
    return this.value;
}
/* edit box button */
function fl_registerEditBox() {
    $('.fl_e').live('click', function(){
        var box = $(this).parents('.fl_box');
        var edit_box = box.find('.fl_edit_box');
        edit_box.toggleClass('hidden');
        
        if (!edit_box.hasClass('hidden')) {
        
            // Edit Saarland live-Box
            if (edit_box.attr('id') == 'saarland_live') {
                var str_twitter_feeds = $.cookie('saarland_magazin_twitter_feeds');
                var str_facebook_feeds = $.cookie('saarland_magazin_facebook_feeds');
                var str_blog_feeds = $.cookie('saarland_magazin_blog_feeds');
                
                if (!(str_twitter_feeds || str_facebook_feeds || str_blog_feeds)) {
                    // No cookie set, show default feeds
                    str_twitter_feeds = $(box).find('input[name=twitter_feeds][rel=default]').map(fl_getValue).get().join(';');
                    str_facebook_feeds = $(box).find('input[name=facebook_feeds][rel=default]').map(fl_getValue).get().join(';');
                    str_blog_feeds = $(box).find('input[name=blog_feeds][rel=default]').map(fl_getValue).get().join(';');
                }
                $(box).find('input').attr('checked', '');
                if (str_twitter_feeds) {
                    var a_twitter_feeds = str_twitter_feeds.split(';');
                    for (i = 0; i < a_twitter_feeds.length; i++) {
                        var feed_id = a_twitter_feeds[i];
                        $(box).find('input[name=twitter_feeds][value="' + feed_id + '"]').attr('checked', 'checked');
                    }
                }
                if (str_facebook_feeds) {
                    var a_facebook_feeds = str_facebook_feeds.split(';');
                    for (i = 0; i < a_facebook_feeds.length; i++) {
                        var feed_id = a_facebook_feeds[i];
                        $(box).find('input[name=facebook_feeds][value="' + feed_id + '"]').attr('checked', 'checked');
                    }
                }
                
                if (str_blog_feeds) {
                    var a_blog_feeds = str_blog_feeds.split(';');
                    for (i = 0; i < a_blog_feeds.length; i++) {
                        var feed_id = a_blog_feeds[i];
                        $(box).find('input[name=blog_feeds][value="' + feed_id + '"]').attr('checked', 'checked');
                    }
                }
            }
            
            // Edit Webcam-Box
            if (edit_box.attr('id') == 'webcam') {
                fl_showSelectedWebcam(box);
            }
            
            // Edit Themenportal-Box
            if (edit_box.attr('id') == 'themenportal') {
                fl_showSelectedThemenportal(box);
            }
        }
    });
    
    $('.fl_box_save').click(function(){
        var box = $(this).parents('.fl_box');
        var edit_box = $(this).parent('.fl_edit_box');
        
        if ($.cookie('fl_magazine_cookies_allowed') == "true") {
            // Save Saarland live-Box
            if (edit_box.attr('id') == 'saarland_live') {
                var twitter_feeds = edit_box.find('input[name=twitter_feeds]:checked').map(fl_getValue).get().join(';');
                $.cookie('saarland_magazin_twitter_feeds', twitter_feeds, { expires: 365, path: '/' });
                
                var facebook_feeds = edit_box.find('input[name=facebook_feeds]:checked').map(fl_getValue).get().join(';');
                $.cookie('saarland_magazin_facebook_feeds', facebook_feeds, { expires: 365, path: '/' });
                
                var blog_feeds = edit_box.find('input[name=blog_feeds]:checked').map(fl_getValue).get().join(';');
                $.cookie('saarland_magazin_blog_feeds', blog_feeds, { expires: 365, path: '/' });
                fl_init_saarland_live_feed(box.attr('id'), false);
            }
            
            if (edit_box.attr('id') == 'webcam') {
                var str_webcam = edit_box.find('input[name=webcam]:checked').eq(0).attr('id');
                $.cookie('fl_webcam', str_webcam, { expires: 365, path: '/' });
                fl_showSelectedWebcam(box);
            }
            
            if (edit_box.attr('id') == 'themenportal') {
                var str_themenportal = edit_box.find('input[name=themenportal]:checked').eq(0).attr('id');
                $.cookie('fl_themenportal', str_themenportal, { expires: 365, path: '/' });
                fl_showSelectedThemenportal(box);
            }  
        }      
        edit_box.addClass('hidden');
    });
}
/** edit magazine */
function fl_registerEditMagazine() {
    if ($('#fl_edit_magazine').length > 0) {
        $('#fl_edit_magazine a').live('click', function() {
            var isactive;
            var linktext;
            var linktext_inactive = $('#fl_edit_magazine a').attr('rel');
            var linktext_active = $('#fl_edit_magazine a').attr('rev');
            
            if ($(this).text() == linktext_inactive) {
                linktext = linktext_active;
                fl_dimMainblockArea(true);
                fl_loadHTMLContent(dl_edit_magazine, '#fl_edit_magazine_layer', function(){
                    fl_updateEditMagazine();
                });
                $('#fl_edit_magazine_layer').customFadeIn(300);
                $(this).text(linktext);
            } else {
                linktext = linktext_inactive;
                fl_dimMainblockArea(false);
                $('#fl_edit_magazine_layer').hide();
                $(this).text(linktext);
                fl_save_all_boxstates();
            }
        });
    }
}
function fl_loadHTMLContent(sourcefile, id, callback) {
    if ($(id).length > 0) {
        if (sourcefile != '' && $(id).data('contentloaded') != '1') {
            $(id).load(sourcefile, function(){
                $(id).data('contentloaded', '1');
                if ($.isFunction(callback))
                    callback();
            });
        } else {
            if ($.isFunction(callback))
                callback();
        }
    }
}
function fl_showMyVideos(data) {
    var feed = data.feed;
    var entries = feed.entry || [];
    var html = ['<ul>'];
    for (var i = 0; i < entries.length; i++) {
        var entry         = entries[i];
        var title         = entry.title.$t;
        var published     = entry.published.$t;
        var url         = entry.link[0].href;
        var pubDate = new Date(published);
        var pubDate_formatted = pubDate.format("dd. mmmm yyyy 'um' HH:MM:ss");
        html.push('<li class="fl_item youtube"><a href="' + url + '" target="_blank">', title, '</a>&nbsp;<span class="fl_smallgrey">' + pubDate_formatted + '</span></li>');
    }
    html.push('</ul>');
    document.getElementById('youtubevideos').innerHTML = html.join('');
} 
function fl_showSelectedWebcam(box) {
    var str_webcam = $.cookie('fl_webcam');
    if (!str_webcam) {
        // No cookie set, show default webcam
        str_webcam = $(box).find('input[name=webcam][rel=default]').eq(0).attr('id');
    }
    if (str_webcam) {
        var active_webcam = $(box).find('input[name=webcam][id=' + str_webcam + ']');
        active_webcam.attr('checked', 'checked');
        var webcam_title = $(box).find('label[for=' + str_webcam + ']').text();
        $('#fl_webcam').html('<h2>' + webcam_title + '</h2><br/><a href="' + active_webcam.attr('rev') + '" target="_blank"><img style="width: 100%" src="' + active_webcam.attr('value') + '" /></a>');
    }
}
function fl_showSelectedThemenportal(box) {
    var str_themenportal = $.cookie('fl_themenportal');
    if (!str_themenportal) {
        // No cookie set, show default themenportal
        str_themenportal = $(box).find('input[name=themenportal][rel=default]').eq(0).attr('id');
    }
    if (str_themenportal) {
        var active_themenportal = $(box).find('input[name=themenportal][id=' + str_themenportal + ']');
        active_themenportal.attr('checked', 'checked');
        var themenportal_title = $(box).find('label[for=' + str_themenportal + ']').text();
        $(box).find('.fl_head h2').html(themenportal_title);
        
        yql = 'select title, link, description, pubDate, thumbnail from rss where url="' + active_themenportal.attr('value') +  '" | sort(field="pubDate",descending="true") | truncate(count=12)';
        rss = active_themenportal.attr('value');
        fl_init_feedbox('themenportal', box, yql, rss);
    }
    
}
/***********************************************************
    FeedLoader-Verarbeitung
***********************************************************/
function fl_init_feedbox(type, selector, yql_query, feed_url) {
    // Direct call doesn't work in IE, replace this when proxy script is available.
    var json_url = '/feed_proxy.php?type=yql&yql=' + escape(yql_query);
    //var json_url = 'http://query.yahooapis.com/v1/public/yql?q=' + escape(yql_query) + '&format=json&callback=';
    $.getJSON(json_url, function(data) {
        var count_items = 0;
        if (type == 'pressedienst') {
            var list = $(selector).find('ul.feed_content');
            var htmlString = '';
            list.empty();
            if (data.query.count > 0) {
                $.each(data.query.results.item, function(i,item){
                    var title = (item.title.content) ? item.title.content : item.title;
                    htmlString = '<li class="fl_item"><a href="' + item.link + '" target="_blank">' + title + '</a><div class="printlink">#</div></li>';
                    list.append(htmlString);
                    count_items++;
                });
                list.find('.fl_item:lt(3)').customFadeIn(300);
            }
            if (feed_url != '')
                $(selector).find('.fl_icon_rss a').attr('href', feed_url);
            else
                $(selector).find('.fl_icon_rss a').hide();
        }
        
        if (type == 'themenportal') {
            var list = $(selector).find('ul.feed_content');
            var teaser = $(selector).find('div.fl_teaser');
            var htmlString = '';
            list.empty();
            teaser.empty();
            if (data.query.count > 0) {
                $(selector).find('div.fl_feed_bar').show();
                $(selector).find('div.fl_textteaser').show();
                $.each(data.query.results.item, function(i,item){
                    var title = (item.title.content) ? item.title.content : item.title;
                    if (count_items == 0) {
                        if (item.thumbnail != null) {
                            teaser.addClass('fl_teaser_image');
                            htmlString = htmlString + '<div class="fl_image"><a href="' + item.link + '"><img src="' + item.thumbnail.url + '" width="'+ item.thumbnail.width + '" height="'+ item.thumbnail.height + '" alt="' + title + '" /></a></div>';
                        } else {
                            teaser.removeClass('fl_teaser_image');
                        }
                        htmlString = htmlString + '<h3><a href="' + item.link + '">' + title + '</a></h3>';
                        htmlString = htmlString + '<p>';
                        if (item.description != null) { 
                            htmlString = htmlString + item.description + '&nbsp;';
                        }
                        htmlString = htmlString + '<a href="' + item.link + '">mehr&nbsp;&raquo;</a></p>';
                        teaser.append(htmlString);
                    } else {
                        htmlString = '<li class="fl_item"><a href="' + item.link + '">' + title + '</a><div class="printlink">#</div></li>';
                        list.append(htmlString);
                    }
                    count_items++;
                });
                list.find('.fl_item:lt(3)').customFadeIn(300);
            } else {
                $(selector).find('div.fl_feed_bar').hide();
                $(selector).find('div.fl_textteaser').hide();
                $(selector).find('.fl_icon_rss a').hide();
                htmlString = '<h3>Zur Zeit gibt es keine Einträge</h3>';
                list.append(htmlString);
            }
            if (feed_url != '' && data.query.count > 0) {
                $(selector).find('.fl_icon_rss a').attr('href', feed_url);
                $(selector).find('.fl_icon_rss a').show();
            } else {
                $(selector).find('.fl_icon_rss a').hide();
            }
        }
        
        if (type == 'rss') {
            var list = $(selector).find('ul.feed_content');
            var htmlString = '';
            list.empty();
            if (data.query.count > 0) {
                var itemlist = data.query.results.item;
                $.each(itemlist, function(i,item){
                    var title = (item.title.content) ? item.title.content : item.title;
                    // Herausparsen von Daten formatiert nach yyyy-MM-dd und Konvertierung in dd. mmmm yyyy
                    var regex = new RegExp("((?:19|20)\\d\\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])", "i");
                    while (title.match(regex)) {
                        var matches = title.match(regex);
                        var currentdate = new Date(matches[1], matches[2], matches[3]);
                        var currentdate_formatted = currentdate.format("dd. mmmm yyyy");
                        
                        title = title.replace(regex, currentdate_formatted);
                    }
                    htmlString = '<li class="fl_item feed"><a href="' + item.link + '" target="_blank">' + title + '</a>&nbsp;<span class="fl_smallgrey">(extern)</span><div class="printlink">#</div></li>';
                    list.append(htmlString);
                    count_items++;
                });
                list.find('.fl_item:lt(3)').customFadeIn(300);
            }
            if (feed_url != '')
                $(selector).find('.fl_icon_rss a').attr('href', feed_url);
            else
                $(selector).find('.fl_icon_rss a').hide();
        }
        
        if (type == 'podcast') {
            var list = $(selector).find('ul.feed_content');
            var htmlString = '';
            list.empty();
            if (data.query.count > 0) {
                $.each(data.query.results.rss.channel.item, function(i,item){
                    var pubDate = new Date(item.pubDate);
                    var pubDate_formatted = pubDate.format("dd. mmmm yyyy 'um' HH:MM:ss");
                    htmlString = '<li class="fl_item podcast"><a href="' + item.link + '" target="_blank">' + item.title + '</a>&nbsp;' + item.description + '&nbsp;<span class="fl_smallgrey">' + pubDate_formatted + '</span><div class="printlink">#</div></li>';
                    list.append(htmlString);
                    count_items++;
                });
                list.find('.fl_item:lt(3)').customFadeIn(300);
            }
            if (feed_url != '')
                $(selector).find('.fl_icon_rss a').attr('href', feed_url);
            else
                $(selector).find('.fl_icon_rss a').hide();
        }
        
        if (type == 'wetter') {
            var list = $(selector).find('div.fl_text');
            var htmlString = '';
            list.empty();
            if (data.query.count > 0) {                    
                function printDay(day, min, max, symbol) {
                    htmlString  = '<div class="boxteaser_col_3">';
                    htmlString += '<a href="#"><img title="' + day + ': ' + min + '&deg;/' + max + '&deg;" src="http://www.saarland.de/systembilder/wetter-' + symbol + '.gif" alt="' + day + ': ' + min + '&deg;/' + max + '&deg;"></a><div class="space"></div><div class="strong">' + day + '</div>' + min + '&deg;/' + max + '&deg;';
                    htmlString += '</div>';
                    list.append(htmlString);
                    count_items++;
                }
                
                var wetter_data = data.query.results.Wetter;
                printDay('Heute', wetter_data.Region.TemperaturminTag, wetter_data.Region.TemperaturmaxTag, wetter_data.Region.SymbolTag);
                printDay(wetter_data.TagA, wetter_data.Region.TemperaturminTagA, wetter_data.Region.TemperaturmaxTagA, wetter_data.Region.SymbolTagA);
                printDay(wetter_data.TagB, wetter_data.Region.TemperaturminTagB, wetter_data.Region.TemperaturmaxTagB, wetter_data.Region.SymbolTagB);
                list.append('<div class="clear"></div>');
                list.customFadeIn(300);
            }
            $(selector).find('.fl_link_bar a').attr('href', feed_url);
        }
        
        if (type == 'mashup') {
            var list = $(selector).find('ul.feed_content');
            var htmlString = '';
            list.empty();
            if (data.query.count > 0) {
                $.each(data.query.results.item, function(i,item){
                    var str_class = '';
                    var pubDate = new Date(item.pubDate);
                    var pubDate_formatted = pubDate.format("dd. mmmm yyyy 'um' HH:MM:ss");
                    if (typeof item.guid == "string" && item.guid.indexOf("twitter") != -1) {
                        htmlString = '<li class="fl_item tw"><a href="' + item.link + '" target="_blank">' + item.title + '</a>&nbsp;<span class="fl_smallgrey">' + pubDate_formatted + '</span></li>';
                    }
                    if (typeof item.guid.content == "string" && item.guid.content.indexOf("facebook") != -1) {
                        if (jQuery.trim(item.title) != '') {
                            htmlString = '<li class="fl_item fb"><a href="' + item.link + '" target="_blank">' + item.title + '</a>&nbsp;<span class="fl_smallgrey">' + pubDate_formatted + '</span></li>';
                        } else {
                            htmlString = '<li class="fl_item fb">' + item.description + '&nbsp;<span class="fl_smallgrey">' + pubDate_formatted + '</span></li>';
                        }
                    }
                    if (typeof item.link == "string" && (item.link.indexOf("blog") != -1 || item.link.indexOf("toscani") != -1)) {
                        htmlString = '<li class="fl_item bl"><a href="' + item.link + '" target="_blank">' + item.title + '</a>&nbsp;<span class="fl_smallgrey">' + pubDate_formatted + '</span></li>';
                    }
                    list.append(htmlString);
                    count_items++;
                });
                list.find('.fl_item:lt(3)').customFadeIn(300);
            }
            if (feed_url != '')
                $(selector).find('.fl_icon_rss a').attr('href', feed_url);
            else
                $(selector).find('.fl_icon_rss a').hide();
        }
        
        if (type == 'flickr') {
            var list = $(selector).find('div.fl_row');
            var htmlString = '';
            list.empty();
            if (data.query.count > 0) {
                $.each(data.query.results.photo, function(i,item){
                    htmlString = '<span><a href="http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank" title="' + item.title + '"><img src="http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_s.jpg" /></a></span>';
                    list.append(htmlString);
                    count_items++;
                });
            }
        }
        
        // Show paging controls
        fl_showPagingControls(selector, count_items);
        
        // Select first tab
        fl_resetBoxTabs(selector);
    });
}
function fl_init_saarland_live_feed(id, static_box) {
    var box_id = '#' + id;
    var a_urls = [];
    var str_twitter_feeds = $.cookie('saarland_magazin_twitter_feeds');
    var str_facebook_feeds = $.cookie('saarland_magazin_facebook_feeds');
    var str_blog_feeds = $.cookie('saarland_magazin_blog_feeds');
    
    if (!(str_twitter_feeds || str_facebook_feeds || str_blog_feeds) || static_box == true) {
        // No cookie set, show default feeds
        str_twitter_feeds = $(box_id).find('input[name=twitter_feeds][rel=default]').map(fl_getValue).get().join(';');
        str_facebook_feeds = $(box_id).find('input[name=facebook_feeds][rel=default]').map(fl_getValue).get().join(';');
        str_blog_feeds = $(box_id).find('input[name=blog_feeds][rel=default]').map(fl_getValue).get().join(';');
    }
    if (str_twitter_feeds) {
        var a_twitter_feeds = str_twitter_feeds.split(';');
        for (i = 0; i < a_twitter_feeds.length; i++) {
            var feed_id = a_twitter_feeds[i];
            a_urls.push("http://twitter.com/statuses/user_timeline/" + feed_id + ".rss");
        }
    }
    if (str_facebook_feeds) {
        var a_facebook_feeds = str_facebook_feeds.split(';');
        for (i = 0; i < a_facebook_feeds.length; i++) {
            var feed_id = a_facebook_feeds[i];
            a_urls.push("http://www.facebook.com/feeds/page.php?format=rss20&id=" + feed_id);
        }
    }
    
    if (str_blog_feeds) {
        var a_blog_feeds = str_blog_feeds.split(';');
        for (i = 0; i < a_blog_feeds.length; i++) {
            var feed_id = a_blog_feeds[i];
            a_urls.push(feed_id);
        }
    }
    yql = 'select * from rss where url in ("' + a_urls.join('", "') +'") LIMIT 300 | sort(field="pubDate", descending="true") | truncate(12)';
    // | sanitize(field="description")
    rss = '';
    fl_init_feedbox('mashup', box_id, yql, rss);
}
/***********************************************************
    REGISTER SORTABLES
***********************************************************/    
function fl_register_sortables() {
if ($(".fl_column").length > 0) {
    $(".fl_column").sortable({
        connectWith: ".fl_column",
        items: ".fl_draggable",
        opacity: 0.65,
        handle: ".fl_head",
        placeholder: "ui-state-highlight",
        distance: 20,
        stop: function(event, ui) {
            fl_save_all_boxstates();
        }
    });
    // $( "div.fl_box" ).disableSelection();
}
}
/***********************************************************
    HANDLING BOX STATES
***********************************************************/    
function fl_save_all_boxstates() {
    fl_save_boxstate('fl_sortables_left');
    fl_save_boxstate('fl_sortables_col_left');
    fl_save_boxstate('fl_sortables_col_right');
}
function fl_save_boxstate(column_id) {
    if ($.cookie('fl_magazine_cookies_allowed') == "true") {
        var boxes = $('#'+column_id).children('*:visible');
        var a_boxes_ids = [];
        boxes.each(function(index, el){
            a_boxes_ids.push(el.id);
        });
    
        $.cookie(column_id, a_boxes_ids.join(';'), { expires: 365, path: '/' });
    }
}
function fl_restore_all_boxstates() {
    if ($.cookie('fl_sortables_left') || $.cookie('fl_sortables_col_left') || $.cookie('fl_sortables_col_right')) {
        // If a saved boxstate ist found, hide all boxes
        $('.fl_box').addClass('hidden');
        
        fl_restore_boxstate('fl_sortables_left');
        fl_restore_boxstate('fl_sortables_col_left');
        fl_restore_boxstate('fl_sortables_col_right');
    }
}
function fl_restore_boxstate(column_id) {
    var cookie_data = $.cookie(column_id);
    if (cookie_data) {
        var a_cookie_data = cookie_data.split(';');
        
        // Restore boxes and show them
        for (i = 0; i < a_cookie_data.length; i++) {
            var box_id = a_cookie_data[i];
            if (box_id != '') {
                $('#'+box_id).appendTo('#'+column_id).removeClass('hidden');
            }
        }
    }
}
function fl_updateEditMagazine() {
    $('ul.fl_checkboxlist li input').each(function(index, el){
        var box_id = $(this).attr('value');
        var box = $("#mag-" + box_id + ":visible");
        if (box.length > 0) {
            $(this).attr('checked', 'checked');
        } else {
            $(this).attr('checked', '');
        }
    });
}
function fl_showCookieMessage() {
    $( "#cookie_message" ).dialog({
        modal: true,
        width: 450,
        title: 'Datenschutz-Hinweis',
        beforeClose: function() {
            // Continue loading
            fl_init_boxes();
        },
        buttons: {
                "Ich akzeptiere": function() {
                    $( this ).dialog( "destroy" );
                    $.cookie('fl_magazine_cookies_allowed', 'true', { expires: 365, path: '/' })
                    // Continue loading
                    fl_init_boxes();
                },
                "Ich akzeptiere NICHT": function() {
                    $( this ).dialog( "destroy" );
                }
            }
    });
}
function fl_init_magazine() {
    if ($.cookie('fl_magazine_cookies_allowed') == "true" || '' != '') {
        // Cookie already set, continue loading
        fl_init_boxes();
    } else {
        // No cookie set, show message
        fl_showCookieMessage();
    }
}
function fl_init_boxes() {
    fl_registerBoxSwitches();
    fl_restore_all_boxstates();
    fl_register_sortables();    
}
function fl_bookmark(url,title) {
    var url = url;
    var title = title;
    if (document.all)
        window.external.AddFavorite(url, title);
    else if (window.sidebar)
        window.sidebar.addPanel(title, url, "")
}
jQuery(function($){
    $.datepicker.regional['de'] = {
        closeText: 'schließen',
        prevText: '&#x3c;zurück',
        nextText: 'Vor&#x3e;',
        currentText: 'heute',
        monthNames: ['Januar','Februar','März','April','Mai','Juni',
        'Juli','August','September','Oktober','November','Dezember'],
        monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
        'Jul','Aug','Sep','Okt','Nov','Dez'],
        dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
        dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
        dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
        weekHeader: 'Wo',
        dateFormat: 'dd.mm.yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['de']);
});
function fl_datepicker(id) {
    if ($(id).length > 0) {
        $(id).datepicker($.datepicker.regional[ "de" ]);
    }
}
/***********************************************************
    $(document) - REGISTER FUNCTIONS
***********************************************************/    
$(document).ready(function() {
    fl_registerTabs();
    fl_registerFeedDefault(3);
    fl_registerFeed();
    /* fl_registerAccordion('#fl_portalbox_frame'); */
    fl_registerToggleContent('#fl_portalbox_frame');
    var keyword = 'Stichworte eingeben'
    if ($('#inputFieldID').length > 0) {
        fl_registerToggleInputField('#inputFieldID', keyword);
        if( $('#inputFieldID2').length > 0 ) {
            $('#inputFieldID2').val(keyword);
        }
    }
    fl_registerEditMagazine();
    fl_registerCloseBox();
    fl_registerEditBox();
    
    /** jquery tools slider */
    if ($('.fl_slider_navigation').length > 0) {
        $(".fl_slider_navigation").tabs(".fl_slider_images > div", {
            // enable "cross-fading" effect
            effect: 'slide',
            fadeOutSpeed: "medium",
            rotate: true,
            
            //clickable: false,
            clickable: true

            
        //}).slideshow( {autopause: false, clickable: false} );
        //}).slideshow( {autopause: true, clickable: true} );
        }).slideshow( {autopause: true, clickable: false, interval: 6000} );

        $(".fl_slider_navigation").data("slideshow").play();
    }
    
    if ($('#fl_magazine_frame').length > 0) {
        fl_init_magazine();
    }
    
    fl_datepicker('#f_date_v');
    fl_datepicker('#f_date_b');
    
    
});

/** slider functions */
function fl_sliderPause() {
    $(".fl_slider_navigation").data("slideshow").pause();
}
function fl_sliderPlay() {
    $(".fl_slider_navigation").data("slideshow").play();
}
