function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt){
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
}

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt){
    carousel.remove(i);
}

function startCarousel(){
    // Since we get all URLs in one file, we simply add all items
    // at once and set the size accordingly.
        
	jQuery.ajax({
		dataType: 'jsonp',
		url: PUBSUB_SERVLET_URL+"?list=urls&callback=?", // this is taken from frontend
		success:function(json){
			if(json.status=="ok"){
				mycarousel_itemList=[];
				for(var i=0;i<json.data.length;i++){
					var o = json.data[i];
					mycarousel_itemList.push(o);
				}
				if(mycarousel_itemList.length>0){
					
					initCarousel(mycarousel_itemList.length-4);
					jQuery(".pubsub").show();
				}else{
					jQuery(".pubsub").hide();
					setTimeout(startCarousel,tryToStartTime);
				}
			}else{
				jQuery(".pubsub").hide();
				setTimeout(startCarousel,tryToStartTime);
			}	
			
		},
		error:function(){
		}
	});
};


function callForFreshData(){
	if(iDetector && !iDetector.isIdle){
		jQuery.ajax({
			dataType: 'jsonp',
			url: PUBSUB_SERVLET_URL+"?list=urls&callback=?", // this is taken from frontend
			success:function(json){
				if(json.status=="ok"){
					var n = mycarousel_itemList.length;
					
					// push new values at the end of the list  
					for(var i=0;i<json.data.length;i++){
						var o = json.data[i];
						mycarousel_itemList.push(o);
					}
					// cut off the start of the list 
					mycarousel_itemList = mycarousel_itemList.slice(n,mycarousel_itemList.length);
					setTimeout(callForFreshData,freshDataCallTime);
				}else{
					setTimeout(callForFreshData,freshDataCallTime);
				}		
			},
			error:function(){
			}
		});
	}else{
		setTimeout(callForFreshData,freshDataCallTime);
	}
}

function fixNo(no){
	if(no<10){
		return "0"+no;
	}
	return no;
}

function getBase(){
	var host = location.host;
	var port="";
	if(host.indexOf(":")==-1){
		// there is no port get it 
		port = location.port; 
		if(port==""){
		   return "http://"+host;
		}else{
		   return "http://"+host+":"+port;
		}
	}else{
	   return "http://"+host;
	}
}

function mycarousel_getItemHTML(o){
	if(o){
		var url = encodeURIComponent(o.url);
		var escapedUrl = o.url.replace(/"/g,"&quot;");
		var dataSource = ""+o.data_source;
		dataSource = dataSource.toLowerCase();
		if(dataSource=="test"){
			dataSource="crawl";
		}
			
		var triplesNo = o.explicitNo;
		
		var today = new Date();
		var d = new Date(o.created);
		var monthNo = d.getMonth();
		var month=[];
		month[0]="Jan";
		month[1]="Feb";
		month[2]="Mar";
		month[3]="Apr";
		month[4]="May";
		month[5]="Jun";
		month[6]="Jul";
		month[7]="Aug";
		month[8]="Sep";
		month[9]="Oct";
		month[10]="Nov";
		month[11]="Dec";
		
		var day = fixNo(d.getDate());
		var hour = fixNo(d.getHours());
		var minute = fixNo(d.getMinutes());
		var second = fixNo(d.getSeconds());
		
		
		if(today.getFullYear()==d.getFullYear() && today.getDay()==d.getDay() && today.getMonth()==d.getMonth()){
			var	created = hour+":"+minute+":"+second;
		}else{
			var	created = d.getFullYear()+"/"+(month[monthNo])+"/"+day+" "+hour+":"+minute+":"+second;
		}
		
		var title = '('+dataSource+')('+created+')  '+triplesNo+' triples from '+escapedUrl;
		var href = getBase()+'/search/page?q='+url+'&qt=term&url='+url+'#triples';
		
		// url can be presented with or without http
		var escapedUrlNoHttp = escapedUrl;//.replace(/http:\/\//,"");
		var domainNoHttp = "http://"+o.domain;
		
		var labelStr = created+' ('+dataSource+') '+triplesNo+' triples '+escapedUrlNoHttp;
		var labelStrNoUrl = created+' ('+dataSource+') '+triplesNo+' triples ';
		var dL = o.domain.length;
		var lineLength = 75; 
		
		if(labelStr.length>lineLength){
			var allowedLengthOfUrl = lineLength - labelStrNoUrl.length;
			if(domainNoHttp.length>allowedLengthOfUrl){
				domainNoHttp = domainNoHttp.substring(0,allowedLengthOfUrl-4);
			}
			escapedUrlNoHttp = domainNoHttp +"..."+ escapedUrlNoHttp.substring( escapedUrlNoHttp.length -( allowedLengthOfUrl - domainNoHttp.length - 3) , escapedUrlNoHttp.length );
		}
		
		if(escapedUrlNoHttp.indexOf("http://")==-1){
			escapedUrlNoHttp = escapedUrlNoHttp.replace(domainNoHttp,'<span class="xmppDomain">'+domainNoHttp+'</span>');
		}else{
			escapedUrlNoHttp = escapedUrlNoHttp.replace(domainNoHttp.replace(/http:\/\//,""),'<span class="xmppDomain">'+domainNoHttp.replace(/http:\/\//,"")+'</span>');
		}
		return  '<div style="font-size:0.9em;line-height:0.9em; color:#777;">'+created+' ('+dataSource+') <a style="color:#2D8FB4"  title="'+title+'" href="'+href+'" target="_blank">'+triplesNo+' triples</a> ' +escapedUrlNoHttp+'</div>';
	}else{
		return '<p>Sorry we are currently experiencing server communication error</p>'
	}
	
}

function initCarousel(){
	jQuery('#jcarousel').jcarousel({
        wrap: 'circular',
        vertical: true,
        scroll: scrollBy,
        start:97,  // put this here to scroll down by first visible elements (prevent to show the latest first)
        // here should be 97 but it does not work in chrome
        animation:"fast",
        itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
        itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback},
        initCallback:function(){
        	jQuery(".jcarousel-prev").hide();
        	jQuery(".jcarousel-next").hide();
        	setTimeout(makeColumnsEqual,200);
        	setTimeout(scrollCarousel,2000);
        }
    });
}

function makeColumnsEqual(){
	//var tallestColumn = equalHeight(jQuery("div.equalColumn"));
	//var entriesBoxH = tallestColumn-70;
	//jQuery(".blogEntriesBox").css("height",entriesBoxH+"px");

}
function scrollCarousel(){
	if(scroll==true){
		jQuery(".jcarousel-prev").click();
	}
	var time = randomXToY(scrollTimeMin,scrollTimeMax);
	scrollTimeout = setTimeout(scrollCarousel,time);
}

function randomXToY(minVal,maxVal,floatVal){
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  var ret = typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal); 
  return ret;
}


//globals used by xmpp widget 
var freshDataCallTime = 20*1000; // 15 sec ~ 15 entries
var tryToStartTime = 10*1000;
var scrollTimeMin = 1000;
var scrollTimeMax = 3000;

var mycarousel_itemList = [];
var scroll = true;
var scrollBy=1;
var scrollTimeout=null;
var triples = 0;
var documents = 0;
var iDetector = null;

// end of globals used by xmpp widget

jQuery(document).ready(function() {        
	// set up a global idle detector	
	 iDetector = new IdleDetector({
	 	inactivityTimeInSec:60, // detect when browser is idle for more then 60 sec 
		idleCallback:function(){
			//console.log("idle");
			// here put code which should be executed when user become inactive
			scroll=false;
			clearTimeout(scrollTimeout);
		},
		backToActivityCallback:function(){
			//console.log("activity starts calling fresh data");
			// here put code which should be executed when user become active again 
			callForFreshData();
			scroll=true;
			scrollCarousel();
		}
	 });
	// end of set up idle detector
	
	//set up a xmpp widget 
	startCarousel();
	callForFreshData();
	jQuery("#jcarousel").hover(
			function(){
				scroll=false;
		        	jQuery(".jcarousel-prev").show();
		        	jQuery(".jcarousel-next").show();
			},
			function(){
				scroll=true;
		        	jQuery(".jcarousel-prev").hide();
		        	jQuery(".jcarousel-next").hide();
			}
	);
	// end of set up xmpp widget
});
