// JavaScript Document
// Created By Jithin Lukose
// 10-Sept-2014 - addHRM-Rss feed.

var serviceURL = localStorage['serviceURL'];
var dataStorage = [];

$(function(){
setTimeout(getRssFeeds,100);
setTimeout(loadOrgNews,50);

	$(document).on('click','.rss-tab-link',function(){
		url = $(this).attr('data-url');
		tab = $(this).parent().index();
		readRssFeed(url, "tab_"+tab);
	});
});


var getRssFeeds = function(){

	$.getJSON(serviceURL + "rss-reader.php?action=listList",function(data){
		var rssList = data.rss;
			
			$.each(rssList,function(index,rssList){
				$('.rss-reader-tabs').find('.rss-tabs').append('<li><a href="#tab_'+index+'" class="rss-tab-link" data-toggle="tab" data-url="'+rssList.rss_url+'">'+rssList.rss_title+'</a></li>');	
				$('.rss-reader-tabs').find('.tab-content').append('<div class="tab-pane" id="tab_'+index+'"> </div>');	
			});
			setTimeout(function(){ 
				$('.rss-tabs li:first a').trigger('click');
			},100);
			
	});
}
var readRssFeed = function(url,tab){
	
	
	if(dataStorage[tab]){
		
		data = dataStorage[tab]
		$('#'+tab).html('');
		$('#'+tab).html('');
		$.each(data,function(index,d){ 
			decode = $("<div/>").html(d.description).text();
			$('#'+tab).append('<H4><a href="'+d.url+'">'+d.title+'</a></H4>'+decode);
		});
		
	}else{
	$.getJSON(serviceURL+"rss-reader.php?action=extract&url="+url,function(data){
		data = data.rss;
		
		dataStorage[tab] = data;
		
		$('#'+tab).html('');
		$.each(data,function(index,d){ 
			decode = $("<div/>").html(d.description).text();
			$('#'+tab).append('<H4><a href="'+d.url+'">'+d.title+'</a></H4>'+decode);
		});

	});
	}
}


var loadOrgNews = function(){
	$.getJSON(serviceURL + "orgnews.php?action=listList",function(data){
		var news = data.news;
		$('.feed-list').parent().css('overflow-y','scroll');
		$.each(news,function(index,news){
			var cateateddate = moment(news.created_time).format('DD-MM-YYYY h:mm a');
			$('.feed-list').append(' <li class="news-title">'+
                                            '<span class="text" style="font-size:14px;">'+news.news_title+'</span>'+
                                            '<small class="label label-danger pull-right"> <i class="fa fa-clock-o"></i> '+cateateddate+'</small>'+
											'<br/><div class="news-details" style="display:none;">'+news.news_description+'</div>'+
                                        '</li>');

		});

	});
}
$(document).on('click','.news-title',function(e){
	$(this).find('.news-details').toggle('blind');
	$this = $(this);
	$('.news-title').not($this).each(function(){
		$(this).find('.news-details').hide('blind');							   
	 });
	e.preventDefault();
});
