/*
 * jquery.socialshareprivacy.js | 2 Klicks fuer mehr Datenschutz
 *
 * http://www.heise.de/extras/socialshareprivacy/
 * http://www.heise.de/ct/artikel/2-Klicks-fuer-mehr-Datenschutz-1333879.html
 *
 * Copyright (c) 2011 Hilko Holweg, Sebastian Hilbig, Nicolas Heiringhoff, Juergen Schmidt,
 * Heise Zeitschriften Verlag GmbH & Co. KG, http://www.heise.de
 *
 * is released under the MIT License http://www.opensource.org/licenses/mit-license.php
 *
 * Spread the word, link to us if you can.
 */
(function($){
    $.fn.socialSharePrivacy = function(options){
        var defaults = {
            'services' : {
                'facebook' : {
                    'status'            : 'off',
                    'dummy_img'         : 'http://tools.werbewind.com/Apis/socialshareprivacy/images/dummy_facebook.png',
                    'txt_info'          : '<strong>2 Klicks f&uuml;r mehr Datenschutz:</strong> Erst wenn Sie hier klicken, wird der Button aktiv und Sie k&ouml;nnen Ihre Empfehlung an Facebook senden. Schon beim Aktivieren werden Daten an Dritte &uuml;bertragen.',
                    'txt_fb_off'        : 'nicht mit Facebook verbunden',
                    'txt_fb_on'         : 'mit Facebook verbunden',
                    'perma_option'      : 'off',
                    'display_name'      : 'Facebook',
                    'referrer_track'    : '',
                    'language'          : 'de_DE'
                },
				'facebookLike' : {
                    'status'            : 'off',
                    'dummy_img'         : 'http://tools.werbewind.com/Apis/socialshareprivacy/images/dummy_facebook_like.png',
                    'txt_info'          : '<strong>2 Klicks f&uuml;r mehr Datenschutz:</strong> Erst wenn Sie hier klicken, wird der Button aktiv und Sie k&ouml;nnen Ihre Empfehlung an Facebook senden. Schon beim Aktivieren werden Daten an Dritte &uuml;bertragen.',
                    'txt_fb_off'        : 'nicht mit Facebook verbunden',
                    'txt_fb_on'         : 'mit Facebook verbunden',
                    'perma_option'      : 'off',
                    'display_name'      : 'Facebook',
                    'referrer_track'    : '',
                    'language'          : 'de_DE'
                },
                'twitter' : {
                    'status'            : 'off', 
                    'dummy_img'         : 'http://tools.werbewind.com/Apis/socialshareprivacy/images/dummy_twitter.png',
                    'txt_info'          : '<strong>2 Klicks f&uuml;r mehr Datenschutz:</strong> Erst wenn Sie hier klicken, wird der Button aktiv und Sie k&ouml;nnen Ihre Empfehlung an Twitter senden. Schon beim Aktivieren werden Daten an Dritte &uuml;bertragen.',
                    'txt_twitter_off'   : 'nicht mit Twitter verbunden',
                    'txt_twitter_on'    : 'mit Twitter verbunden',
                    'perma_option'      : 'off',
                    'display_name'      : 'Twitter',
                    'referrer_track'    : '', 
                    'tweet_text'        : getTweetText
                },
                'gplus' : {
                    'status'            : 'off',
                    'dummy_img'         : 'http://tools.werbewind.com/Apis/socialshareprivacy/images/dummy_gplus.png',
                    'txt_info'          : '<strong>2 Klicks f&uuml;r mehr Datenschutz:</strong> Erst wenn Sie hier klicken, wird der Button aktiv und Sie k&ouml;nnen Ihre Empfehlung an Google+ senden. Schon beim Aktivieren werden Daten an Dritte &uuml;bertragen.',
                    'txt_gplus_off'     : 'nicht mit Google+ verbunden',
                    'txt_plus_on'       : 'mit Google+ verbunden',
                    'perma_option'      : 'off',
                    'display_name'      : 'Google+',
                    'referrer_track'    : '',
                    'language'          : 'de'
                }
            },
            'info_link'         : 'http://www.heise.de/ct/artikel/2-Klicks-fuer-mehr-Datenschutz-1333879.html',
            'txt_help'          : 'Wenn Sie diese Felder durch einen Klick aktivieren, werden Informationen an Facebook, Twitter oder Google in die USA &uuml;bertragen und unter Umst&auml;nden auch dort gespeichert. N&auml;heres erfahren Sie durch einen Klick auf das <em>i</em>.',
            'settings_perma'    : 'Dauerhaft aktivieren und Daten&uuml;ber&shy;tragung zustimmen:',
            'cookie_path'       : '/',
            'cookie_domain'     : document.location.host,
            'cookie_expires'    : '365',
            'css_path'          : 'http://tools.werbewind.com/Apis/socialshareprivacy/socialshareprivacy.css',
			'facebookProfile'	: ''
        };

        // Standardwerte des Plug-Ings mit den vom User angegebenen Optionen ueberschreiben
        var options = $.extend(true, defaults, options);

        if(options.services.facebook.status == 'on' || options.services.twitter.status == 'on' || options.services.gplus.status == 'on'){
            $('head').append('<link rel="stylesheet" type="text/css" href="'+options.css_path+'" />');
            $(this).prepend('<ul id="social_share_privacy_area" style="list-style-type:none;margin:0;padding:0"></ul>');
            var context = $('#social_share_privacy_area', this);
            // als URL wird erstmal die derzeitige Dokument-URL angenommen
            var uri = document.location.href;
            // ist eine kanonische URL hinterlegt wird diese verwendet
            var canonical = $("link[rel=canonical]").attr("href");
            if(canonical){
                if(canonical.indexOf("http") <= 0){
                    canonical = document.location.protocol+"//"+document.location.host+document.location.port+canonical;
                }
                uri = canonical;
            }
        }

        // Text kuerzen und am Ende mit … versehen, sofern er abgekuerzt werden musste
        function abbreviateText(text, length){
            var abbreviated = decodeURIComponent(text);
            if(abbreviated.length <= length){
                return text;
            }

            var lastWhitespaceIndex = abbreviated.substring(0, length - 1).lastIndexOf(' ');
            abbreviated = encodeURIComponent(abbreviated.substring(0, lastWhitespaceIndex)) + "…";

            return abbreviated;
        }

        // Meta-Wert abfragen
        function getMeta(name){
            var metaContent = jQuery('meta[name="' + name + '"]').attr('content');
            return metaContent ? metaContent : '';
        }
        
        // Tweet-Text
        function getTweetText(){
            // Titel aus <meta name="DC.title"> und <meta name="DC.creator"> wenn vorhanden, sonst <title>
            var title = getMeta('DC.title');
            var creator = getMeta('DC.creator');
            if(title.length > 0){
                if(creator.length > 0){
                    title = title+' - '+creator;
                }
            }
            else{
                title = $('title').text();
            }
            return encodeURIComponent(title);
        }

        return this.each(function(){
            // Facebook Recommend Button
            if(options.services.facebook.status == 'on'){
                // Kontrolle ob Facebook App-ID hinterlegt ist, da diese noetig fuer den Empfehlen-Button ist
                
                    var fb_enc_uri = encodeURIComponent(uri+options.services.facebook.referrer_track);
					if(options.services.facebookProfile != ''){
						fb_enc_uri = encodeURIComponent(options.services.facebookProfile);
					}
                    var fb_code = '<iframe src="http://www.facebook.com/plugins/like.php?locale='+options.services.facebook.language+'&amp;href='+fb_enc_uri+'&amp;send=false&amp;layout=button_count&amp;width=120&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"></iframe>';
                    var fb_dummy_btn = '<img src="'+options.services.facebook.dummy_img+'" alt="Facebook &quot;Like&quot;-Dummy" class="fb_like_privacy_dummy" />';

                    context.append('<li class="facebook help_info" style="display:inline-block;margin:0"><span class="info" style="display:none">'+options.services.facebook.txt_info+'</span><div class="fb_like dummy_btn" style="margin-right:10px">'+fb_dummy_btn+'</div></li>');

                    var $container_fb = $('li.facebook', context);

                    $('li.facebook div.fb_like img.fb_like_privacy_dummy,li.facebook span.switch', context).live('click', function(){
                            $container_fb.addClass('info_off');
                            $container_fb.find('img.fb_like_privacy_dummy').replaceWith(fb_code);
                    });
                
            }
			
			// Facebook Like button
            if(options.services.facebookLike.status == 'on'){
                // Kontrolle ob Facebook App-ID hinterlegt ist, da diese noetig fuer den Empfehlen-Button ist
                
                    var fbl_enc_uri = encodeURIComponent(uri+options.services.facebookLike.referrer_track);
					if(options.services.facebookProfile != ''){
						fbl_enc_uri = encodeURIComponent(options.services.facebookProfile);
					}
                    var fbl_code = '<iframe src="http://www.facebook.com/plugins/like.php?locale='+options.services.facebookLike.language+'&amp;href='+fbl_enc_uri+'&amp;send=false&amp;layout=button_count&amp;width=120&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"></iframe>';
                    var fbl_dummy_btn = '<img src="'+options.services.facebookLike.dummy_img+'" alt="Facebook &quot;Like&quot;-Dummy" class="fb_second_privacy_dummy" />';

                    context.append('<li class="facebook_second help_info" style="display:inline-block;margin:0"><span class="info" style="display:none">'+options.services.facebook.txt_info+'</span><div class="fb_second dummy_btn" style="margin-right:10px">'+fbl_dummy_btn+'</div></li>');

                    var $container_fbl = $('li.facebook_second', context);

                    $('li.facebook_second div.fb_second img.fb_second_privacy_dummy', context).live('click', function(){
						$container_fbl.addClass('info_off');
                    	$container_fbl.find('img.fb_second_privacy_dummy').replaceWith(fbl_code);
                    });
                
            }

            // Twitter
            if(options.services.twitter.status == 'on'){
                // 120 = Restzeichen-Anzahl nach automatischem URL-Kuerzen durch Twitter mit t.co
                var text = options.services.twitter.tweet_text;
                if(typeof(text) == 'function'){
                    text = text();
                }
                text = abbreviateText(text,'120');
                
                var twitter_enc_uri = encodeURIComponent(uri+options.services.twitter.referrer_track);
                var twitter_count_url = encodeURIComponent(uri);
                var twitter_code = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url='+twitter_enc_uri+'&amp;counturl='+twitter_count_url+'&amp;text='+text+'&amp;count=none"></iframe>';
                var twitter_dummy_btn = '<img src="'+options.services.twitter.dummy_img+'" alt="&quot;Tweet this&quot;-Dummy" class="tweet_this_dummy" />';
                
                context.append('<li class="twitter help_info" style="display:inline-block;margin:0"><span class="info" style="display:none">'+options.services.twitter.txt_info+'</span><div class="tweet dummy_btn" style="margin-right:10px">'+twitter_dummy_btn+'</div></li>');

                var $container_tw = $('li.twitter', context);
                
                $('li.twitter div.tweet img', context).live('click', function(){
					$container_tw.addClass('info_off');
                	$container_tw.find('img.tweet_this_dummy').replaceWith(twitter_code);
                });
            }

            // Google+
            if(options.services.gplus.status == 'on'){
                // fuer G+ wird die URL nicht encoded, da das zu einem Fehler fuehrt
                var gplus_uri = uri+options.services.gplus.referrer_track;
                var gplus_code = '<div class="g-plusone" data-size="medium" data-count="false" data-href="'+gplus_uri+'"></div><script type="text/javascript">window.___gcfg = {lang: "'+options.services.gplus.language+'"}; (function(){ var po = document.createElement("script"); po.type = "text/javascript"; po.async = true; po.src = "https://apis.google.com/js/plusone.js"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(po, s); })(); </script>';
                var gplus_dummy_btn = '<img src="'+options.services.gplus.dummy_img+'" alt="&quot;Google+1&quot;-Dummy" class="gplus_one_dummy" />';

                context.append('<li class="gplus help_info" style="display:inline-block;;margin:0"><span class="info" style="display:none">'+options.services.gplus.txt_info+'</span><div class="gplusone dummy_btn" style="margin-right:10px">'+gplus_dummy_btn+'</div></li>');

                var $container_gplus = $('li.gplus', context);

                $('li.gplus div.gplusone img', context).live('click', function(){
					$container_gplus.addClass('info_off');
                	$container_gplus.find('img.gplus_one_dummy').replaceWith(gplus_code);
                });
            }

            // Info-Overlays mit leichter Verzoegerung einblenden
            $('.help_info:not(.info_off)', context).live('mouseenter', function(){
                var $info_wrapper = $(this);
                var timeout_id = window.setTimeout(function(){ $($info_wrapper).addClass('display'); }, 150);
                $(this).data('timeout_id',timeout_id);
            });
            $('.help_info', context).live('mouseleave', function(){
                var timeout_id = $(this).data('timeout_id');
                window.clearTimeout(timeout_id);
                if($(this).hasClass('display')){
                    $(this).removeClass('display');
                }
            });

            
            
        });
    }
})(jQuery);

