// --------------------Cookies Portlets ---------------------
var setCookieExpiry = 180;
function saveOrder(column, cookiename)
{
   $.cookie(cookiename, $(column).sortable("toArray"), { expires: setCookieExpiry, path: "/" });
}

function loadOrder(column, cookiename)
{
   var list = $(column);
   if (list == null) return;

   var cookie = $.cookie(cookiename);
   if (!cookie) return;

   var IDs = cookie.split(",");
   var rebuild = new Array();
   var index = 0;

   for (var col=0; col<$(".column").size(); col++)
   {
      var id = $(".column")[col].id;
      var items = $("#" + id).sortable("toArray");

      for (var i=0, len=items.length; i<len; i++)
      {
         rebuild[items[i]] = items[i];
         index++;
      }
   }

   for (var i=0, len=IDs.length; i<len; i++)
   {
      var itemID = IDs[i];
      if (itemID in rebuild)
      {
         var item = rebuild[itemID];
         var child = $(".ui-sortable").children("#" + item);
         var savedOrd = $(".ui-sortable").children("#" + itemID);
         child.remove();
         $(".ui-sortable").filter(column).append(savedOrd);
      }
   }
}

$(function()
// ----------------------------Portlets part----------------------
{
	$("#col1").sortable({ connectWith: '.column',
			   cursor: "move",
			   update: function() { saveOrder("#col1", "portletOrder1"); }
			 });
	$("#col2").sortable({ connectWith: '.column',
			   cursor: "move",
			   update: function() { saveOrder("#col2", "portletOrder2"); }
			 });
	$("#col3").sortable({ connectWith: '.column',
			   cursor: "move",
			   update: function() { saveOrder("#col3", "portletOrder3"); }
			 });
	$(".portlet").addClass("ui-helper-clearfix")
	.find(".portlet-header")
		.prepend('<span class="feed-icon feed-icon-twitter" title="Type de Flux (RSS ou Twitter)" ></span>')
	.end()
	.find(".portlet-footer")
		.prepend('<span class="ui-icon ui-icon-plus"></span>')
	.end()
	.find(".twitter-footer")
		.prepend('<span class="ui-icon ui-icon-plus"></span>')
	.end()

	loadOrder("#col1", "portletOrder1");
	loadOrder("#col2", "portletOrder2");
	loadOrder("#col3", "portletOrder3");
	
// -----------------TWEETS section----------------------
	var twuser = ["lemondefr","JournalExpress","LesEchos","LeHuffPost","Marianne2fr","lequipe","LeFigaro_France","LePoint","france_soir","leparisien_fr","Rue89","LaTribune","liberation_info","LeNouvelObs","leJDD","LaCroixCom","20minutes","humanite_fr"];
	
// -----------------Toggle tweets P1 for EACH portlet----------------------	
 	$.each(twuser, function(index, value) {
	
		$(".feed-icon").toggle(function(){
			
			$(this).addClass("feed-icon-rss");
			$(this).parents(".portlet:first").find(".name_paper").addClass("hide");
			$(this).parents(".portlet:first").find(".name_twuser").removeClass("hide");
			$(this).parents(".portlet:first").find(".feed-content").hide();
			$(this).parents(".portlet:first").find(".p2" + value).hide();
			$(this).parents(".portlet:first").find(".twitter-content").show();
			$(this).parents(".portlet:first").find(".p1" + value).show();
			$(this).parents(".portlet:first").find(".pagetweets2").addClass("hide");
			$(this).parents(".portlet:first").find(".pagetweets1").removeClass("hide");
			$(this).parents(".portlet:first").find(".twitter-footer .ui-icon").removeClass("ui-icon-minus");
			$(this).parents(".portlet:first").find(".p1" + value).tweet({
				username: "" + value,
				page: 1,
			});
				
		}, function (){
			
			$(this).removeClass("feed-icon-rss");
			$(this).parents(".portlet:first").find(".name_twuser").addClass("hide");
			$(this).parents(".portlet:first").find(".name_paper").removeClass("hide");
			$(this).parents(".portlet:first").find(".twitter-content").hide();
			$(this).parents(".portlet:first").find(".feed-content").show();
		
		});
	});

	// -----------------Toggle tweets P2 for EACH portlet----------------------	
 	$.each(twuser, function(index, value) {
	
		$(".twitter-footer .ui-icon").toggle(function(){
			
			$(this).addClass("ui-icon-minus");
			$(this).parents(".portlet:first").find(".p1" + value).hide();
			$(this).parents(".portlet:first").find(".p2" + value).show();
			$(this).parents(".portlet:first").find(".p2" + value).tweet({
				username: "" + value,
				page: 2,
			});
			$(this).parents(".portlet:first").find(".pagetweets1").addClass("hide");
			$(this).parents(".portlet:first").find(".pagetweets2").removeClass("hide");
		
		}, function (){
			
			$(this).removeClass("ui-icon-minus");			
			$(this).parents(".portlet:first").find(".p2" + value).hide();
			$(this).parents(".portlet:first").find(".p1" + value).show();
			$(this).parents(".portlet:first").find(".p1" + value).tweet({
				username: "" + value,
				page: 1,
			});
			$(this).parents(".portlet:first").find(".pagetweets2").addClass("hide");
			$(this).parents(".portlet:first").find(".pagetweets1").removeClass("hide");
			
		});
	});
		
	
// --------------TOGGLE ALL TWEETS ALL PORTLETS-------------------
	/* $("#toggle_tweets").toggle(function(){
		$(this).addClass("feed-icon-rss");
		$("#toggleall").addClass("hide");
		$("#toggle_photos").addClass("hide");
		$("#toggle_dates").addClass("hide");
		$(".feed-icon").addClass("feed-icon-rss");
		$(".name_paper").addClass("hide");
		$(".name_twuser").removeClass("hide");
		$(".portlet").find(".feed-content").hide();
		$(".portlet").find(".twitter-content").show();			
	}, function (){	
		$(this).removeClass("feed-icon-rss");
		$("#toggleall").removeClass("hide");
		$("#toggle_photos").removeClass("hide");
		$("#toggle_dates").removeClass("hide");
		$(".feed-icon").removeClass("feed-icon-rss");		
		$(".name_twuser").addClass("hide");
		$(".name_paper").removeClass("hide");
		$(".portlet").find(".twitter-content").hide();
		$(".portlet").find(".feed-content").show();
	});	  */

//----------- Toggle more / less NEWS items each portlet-----------------
	$(".portlet-footer .ui-icon").click(function()
	{
	  $(this).toggleClass("ui-icon-minus");
	  $(this).parents(".portlet:first").find(".portlet-content2").toggle('blind');
	});	
	
//------------ Toggle more / less NEWS items all portlets---------------	
	var moreless = $.cookie('show_items'); 
	if (moreless == null) { var moreless = 'less';}
	if (moreless == 'less') {
		$(".portlet-footer .ui-icon").removeClass("ui-icon-minus");
		$(".portlet").find(".portlet-content2").hide();
	  }
	if (moreless == 'more') {
		$(".portlet-footer .ui-icon").addClass("ui-icon-minus");
		$(".portlet").find(".portlet-content2").show();
	   };
	   
	$("#toggleall").toggle(function(){	
	if (moreless == 'less') 
	{	
		$(".portlet-footer .ui-icon").addClass("ui-icon-minus");
		$(".portlet").find(".portlet-content2").show();
		$.cookie('show_items', 'more',{ expires: 99 });
	} 
	if (moreless == 'more') 
	{
		$(".portlet-footer .ui-icon").removeClass("ui-icon-minus");
		$(".portlet").find(".portlet-content2").hide();
		$.cookie('show_items', 'less',{ expires: 99 });
	} 
	}, function (){
	if (moreless == 'less') 
	{
		$(".portlet-footer .ui-icon").removeClass("ui-icon-minus");
		$(".portlet").find(".portlet-content2").hide();
		$.cookie('show_items', 'less',{ expires: 99 });
	} 
	if (moreless == 'more') 
	{	
		$(".portlet-footer .ui-icon").addClass("ui-icon-minus");
		$(".portlet").find(".portlet-content2").show();
		$.cookie('show_items', 'more',{ expires: 99 });
	} 
	});
	    
//---------------------- Move Portlets---------------------------
	$(".moveall").click(function()
		{			
			$(".portlet-content").toggle();
			$(".feed-icon").toggle();
			$("#movetext").toggle();
			$("#main").toggleClass("pagewidth2");
			$(".searchform").toggleClass("hide");
			$("#theme").toggleClass("hide");			
		}
	);

//-----------Clear portlets positions cookie and reload--------
	$("#reset").click(function()
		{
			$.cookie("portletOrder1", null);
			$.cookie("portletOrder2", null);
			$.cookie("portletOrder3", null);
			location.reload();
		});	
  	
   $(".column").disableSelection();
   
// ------------------Toggle photos----------------------
   $("#toggle_photos").click(function()
		{	
			$(".imglaune").toggleClass("hide");			
		}
	);	

// ------------------Show/hide dates on click------------------------
 	$("#toggle_dates").click(function()
		{	
			$(".showdate").toggleClass("hide");			
		}
	);	
   
// -----------------------Font Resize part----------
   
	var affichage = $.cookie('font_size'); 
	if (affichage == null) { var affichage = 'normal';}
	if (affichage == 'normal') {
		$(".column").removeClass("font-size1").addClass("font-size2");
	  }
	if (affichage == 'bigfont') {
		$(".column").removeClass("font-size2").addClass("font-size1");
	   }
		   
	$("#changefont").toggle(function(){	
	if (affichage == 'normal') 
	{	
		$(".column").removeClass("font-size2").addClass("font-size1");
		$.cookie('font_size', 'bigfont',{ expires: 99 });
	} 
	if (affichage == 'bigfont') 
	{
		$(".column").removeClass("font-size1").addClass("font-size2");
		$.cookie('font_size', 'normal',{ expires: 99 });
	} 
	}, function () {
	if (affichage == 'normal') 
	{
		$(".column").removeClass("font-size1").addClass("font-size2");
		$.cookie('font_size', 'normal',{ expires: 99 });
	} 
	if (affichage == 'bigfont') 
	{	
		$(".column").removeClass("font-size2").addClass("font-size1");
		$.cookie('font_size', 'bigfont',{ expires: 99 });
	} 
	});
	
// ----------------------If Javascrit Browser enabled----------------
	$('HTML').addClass('JS'); 

// ----------------------Clear input search on click------------------
	$("#reset_input").click(function()
	{			
	$(':input').val("");
	});
	
// -------------------Show dates on Item mouse over------------------
/* 	$(".linkarticle").hover(function() {
		$(this).parents(".lineitems:first").find(".showdate").removeClass('hide');
    }, function() {
		$(this).parents(".lineitems:first").find(".showdate").addClass('hide');
    }); */

});
// ----------------------------END JQUERY----------------------

//-----------------------Functions--------------------
// ----------------------Search feature---------------
/* New from Rob Nitti, who credits 
 * http://bytes.com/groups/javascript/145532-replace-french-characters-form-inp
 * The code finds accented vowels and replaces them with their unaccented version. */
function stripVowelAccent(str)
{
	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE2]/g,
		/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
		/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
		/[\xD2-\xD4]/g, /[\xF2-\xF4]/g,
		/[\xD9-\xDB]/g, /[\xF9-\xFB]/g ];

	var repChar=['A','a','E','e','I','i','O','o','U','u'];

	for(var i=0; i<rExps.length; ++i)
		str=str.replace(rExps[i],repChar[i]);

	return str;
}

/* Modification of */
/* http://www.kryogenix.org/code/browser/searchhi/ */
/* See: */
/*   http://www.tedpavlic.com/post_highlighting_search_results_with_ted_searchhi_javascript.php */    
/*   http://www.tedpavlic.com/post_inpage_highlighting_example.php */
/* for additional modifications of this base code. */
function highlightWord(node,word) {
	// Iterate into this nodes childNodes
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
			highlightWord(node.childNodes[hi_cn],word);
		}
	}

	// And do this node itself
	if (node.nodeType == 3) { // text node
		tempNodeVal = stripVowelAccent(node.nodeValue.toLowerCase());
		tempWordVal = stripVowelAccent(word.toLowerCase());
		if (tempNodeVal.indexOf(tempWordVal) != -1) {
			pn = node.parentNode;
			if (pn.className != "searchword") {
				// word has not already been highlighted!
				nv = node.nodeValue;
				ni = tempNodeVal.indexOf(tempWordVal);
				// Create a load of replacement nodes
				before = document.createTextNode(nv.substr(0,ni));
				docWordVal = nv.substr(ni,word.length);
				after = document.createTextNode(nv.substr(ni+word.length));
				hiwordtext = document.createTextNode(docWordVal);
				hiword = document.createElement("span");
				hiword.className = "searchword";
				hiword.appendChild(hiwordtext);
				pn.insertBefore(before,node);
				pn.insertBefore(hiword,node);
				pn.insertBefore(after,node);
				pn.removeChild(node);
			}
		}
	}
}

function unhighlight(node) {
	// Iterate into this nodes childNodes
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
			unhighlight(node.childNodes[hi_cn]);
		}
	}

	// And do this node itself
	if (node.nodeType == 3) { // text node
		pn = node.parentNode;
		if( pn.className == "searchword" ) {
			prevSib = pn.previousSibling;
			nextSib = pn.nextSibling;
			nextSib.nodeValue = prevSib.nodeValue + node.nodeValue + nextSib.nodeValue;
			prevSib.nodeValue = '';
			node.nodeValue = '';
		}
	}
}

function localSearchHighlight(searchStr) {
	if (!document.createElement) return;
        if (searchStr == '') return;
	// Trim leading and trailing spaces after unescaping
	searchstr = unescape(searchStr).replace(/^\s+|\s+$/g, "");
	if( searchStr == '' ) return;
	phrases = searchStr.replace(/\+/g,' ').split(/\"/);
	// Use this next line if you would like to force the script to always
	// search for phrases. See below as well!!!
	phrases = new Array(); phrases[0] = ''; phrases[1] = searchStr.replace(/\+/g,' ');
	for(p=0;p<phrases.length;p++) {
	        phrases[p] = unescape(phrases[p]).replace(/^\s+|\s+$/g, "");
		if( phrases[p] == '' ) continue;
		if( p % 2 == 0 ) words = phrases[p].replace(/([+,()]|%(29|28)|\W+(AND|OR)\W+)/g,' ').split(/\s+/);
		else { words=Array(1); words[0] = phrases[p]; }
               	for (w=0;w<words.length;w++) {
			if( words[w] == '' ) continue;
			highlightWord(document.getElementsByTagName("body")[0],words[w]);
        	}
	}
}

function date() {
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var dayarray=new Array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi")
var montharray=new Array("Janvier","Fevrier","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Decembre")
document.write(dayarray[day].bold()+" "+daym+" "+montharray[month]+" "+year)
}
