
// jquery.tweet.js - See http://tweet.seaofclouds.com/ or https://github.com/seaofclouds/tweet for more info
// Copyright (c) 2008-2011 Todd Matthews & Steve Purcell
(function($) {
  $.fn.tweet = function(o){
    var s = $.extend({
      username: "cleiss_fr",                    // [string or array] required unless using the 'query' option; one or more twitter screen names (use 'list' option for multiple names, where possible)
      list: null,                               // [string]   optional name of list belonging to username
      favorites: false,                         // [boolean]  display the user's favorites instead of his tweets
      query: null,                              // [string]   optional search query (see also: http://search.twitter.com/operators)
      count: 8,                                 // [integer]  how many tweets to display?
      fetch: null,                              // [integer]  how many tweets to fetch via the API (set this higher than 'count' if using the 'filter' option)
      page: 1,                                  // [integer]  which page of results to fetch (if count != fetch, you'll get unexpected results)
      retweets: false,                           // [boolean]  whether to fetch (official) retweets (not supported in all display modes)
      intro_text: "Actualité de la protection sociale dans le monde",                         // [string]   do you want text BEFORE your your tweets?
      outro_text: "&raquo; suivez @cleiss_fr sur twitter",                         // [string]   do you want text AFTER your tweets?
      loading_text: null,                       // [string]   optional loading text, displayed while tweets load
      refresh_interval: null ,                  // [integer]  optional number of seconds after which to reload tweets
      twitter_url: "twitter.com",               // [string]   custom twitter url, if any (apigee, etc.)
      twitter_api_url: "api.twitter.com",       // [string]   custom twitter api url, if any (apigee, etc.)
      twitter_search_url: "search.twitter.com", // [string]   custom twitter search url, if any (apigee, etc.)
      template: "{text}",   // [string or function] template used to construct each tweet <li> - see code for available vars
      comparator: function(tweet1, tweet2) {    // [function] comparator used to sort tweets (see Array.sort)
        return tweet2["tweet_time"] - tweet1["tweet_time"];
      },
      filter: function(tweet) {                 // [function] whether or not to include a particular tweet (be sure to also set 'fetch')
        return true;
      }
    }, o);

    var url_regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;

    // Expand values inside simple string templates with {placeholders}
    function t(template, info) {
      if (typeof template === "string") {
        var result = template;
        for(var key in info) {
          var val = info[key];
          result = result.replace(new RegExp('{'+key+'}','g'), val === null ? '' : val);
        }
        return result;
      } else return template(info);
    }
    // Export the t function for use when passing a function as the 'template' option
    $.extend({tweet: {t: t}});

    function replacer (regex, replacement) {
      return function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(regex, replacement));
        });
        return $(returning);
      };
    }

    function escapeHTML(s) {
      return s.replace(/</g,"&lt;").replace(/>/g,"^&gt;");
    }

    $.fn.extend({
      linkUser: replacer(/(^|[\W])@(\w+)/gi, "$1@<a href=\"http://"+s.twitter_url+"/$2\">$2</a>"),
      // Support various latin1 (\u00**) and arabic (\u06**) alphanumeric chars
      linkHash: replacer(/(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi,
                         ' <a href="http://'+s.twitter_search_url+'/search?q=&tag=$1&lang=all'+((s.username && s.username.length == 1 && !s.list) ? '&from='+s.username.join("%2BOR%2B") : '')+'">#$1</a>')
    });



    function linkURLs(text, entities,date_str) {
     	var d= date_str.replace(/^([a-z]{3}) ([a-z]{3}) (\d\d?) (.*) (\d{4})$/i, '$3 $2').toLowerCase();
        if (d.substring(0,1)=='0') d=d.substring(1);
	if (entities.length>0) {
		var entity = entities[0];
		url = escapeHTML(entity.expanded_url);
		urldomain=escapeHTML(entity.display_url);
		indi=entity.indices[0];
		domaine = urldomain.substring(0,urldomain.indexOf('/', 0))
        	return "<b>"+d.replace("feb","fev")+"</b><a href=\""+escapeHTML(url)+"\">"+text.substring(0,indi)+" <small>"+domaine+"</small></a>";
      }
    }



    function parse_date(date_str) {
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    }

    


    function build_api_url() {
      var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
      var count = (s.fetch === null) ? s.count : s.fetch;
      var common_params = '&include_entities=1&callback=?';
      if (s.list) {
        return proto+"//"+s.twitter_api_url+"/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?page="+s.page+"&per_page="+count+common_params;
      } else if (s.favorites) {
        return proto+"//"+s.twitter_api_url+"/favorites/"+s.username[0]+".json?page="+s.page+"&count="+count+common_params;
      } else if (s.query === null && s.username.length == 1) {
        return proto+'//'+s.twitter_api_url+'/1/statuses/user_timeline.json?screen_name='+s.username[0]+'&count='+count+'&page='+s.page+common_params;
      } else {
        var query = (s.query || 'from:'+s.username.join(' OR from:'));
        return proto+'//'+s.twitter_search_url+'/search.json?&q='+encodeURIComponent(query)+'&rpp='+count+'&page='+s.page+common_params;
      }
    }

    

    // Convert twitter API objects into data available for
    // constructing each tweet <li> using a template
    function extract_template_data(item){
      var o = {};
      o.item = item;      
      o.retweet = typeof(item.retweeted_status) != 'undefined';
      o.tweet_time = parse_date(item.created_at);
      o.entities = item.entities ? (item.entities.urls || []).concat(item.entities.media || []) : [];
     
      o.tweet_text = $([linkURLs(item.text, o.entities,item.created_at)])[0];

      // Default spans, and pre-formatted blocks for common layouts
      
      o.text = t('<span class="tweet_text">{tweet_text}</span>', o);
      
      return o;
    }

    return this.each(function(i, widget){
      var list = $('<ul class="tweet_list">');
      var intro = '<h2>'+s.intro_text+'</h2>';
      var outro = '<a class="twittus" href="http://twitter.com/#!/Cleiss_fr">'+s.outro_text+'</a>';
      var loading = $('<p class="loading">'+s.loading_text+'</p>');

      if(s.username && typeof(s.username) == "string"){
        s.username = [s.username];
      }

      $(widget).bind("tweet:load", function(){
        if (s.loading_text) $(widget).empty().append(loading);
        $.getJSON(build_api_url(), function(data){
          $(widget).empty().append(list);
          if (s.intro_text) list.before(intro);
          list.empty();

          var tweets = $.map(data.results || data, extract_template_data);
          tweets = $.grep(tweets, s.filter).sort(s.comparator).slice(0, s.count);
          list.append($.map(tweets, function(o) { return "<li>" + t(s.template, o) + "</li>"; }).join('')).
              children('li:first').addClass('tweet_first').end();

          if (s.outro_text) list.after(outro);
          $(widget).trigger("loaded").trigger((tweets.length === 0 ? "empty" : "full"));
          if (s.refresh_interval) {
            window.setTimeout(function() { $(widget).trigger("tweet:load"); }, 1000 * s.refresh_interval);
          }
         $("#tweets").addClass("dossier");
        });
				
      }).trigger("tweet:load");
    });
  };
})(jQuery);
var offs=0;
var pause="off";
var nb;
$(document).ready(function() {
	$("#decryptage").mouseover(function(){pause="on";}).mouseout(function(){pause="off";});
	nb=$(".sommaire-small-carousel").size()-1;
	
	$(".sommaire-small-carousel:gt(0)").hide();
	$("#decryptage").append("<div id='nextprev'></div>")
	offs=nb;
	lapos=nb;
	for (i=nb+1;i>0;i--){
		$("#nextprev").prepend("<span>&bull;</span>");
	}
	$("#nextprev span:last").addClass('over');
	$("#nextprev span").mouseover(function(){
		offs=$("#nextprev span").index(this);
		lapos=nb-offs;
		$("#nextprev span").removeClass('over');
		$(this).addClass('over');
		$(".sommaire-small-carousel").hide();
		$(".sommaire-small-carousel:eq("+lapos+")").show();	
	})

	$("#tweets").tweet();
	window.setTimeout(rotate, 10000);



})

function rotate(){
if (pause!="on") {
		offs--;
		if (offs<0) offs=nb;
		showme=nb-offs;
		$(".sommaire-small-carousel").hide();

		$(".sommaire-small-carousel:eq("+showme+")").show();
		$("#nextprev span").removeClass('over');
		$("#nextprev span:eq("+offs+")").addClass('over');
		
	}
	if (offs==nb) window.setTimeout(rotate, 10000); else window.setTimeout(rotate, 3000);
}
