function getClickedIDs(){
	//get an array of all clicked categories
	var ids = [];
	$("a.clicked").each(function () { 
		//alert(this.id);
		ids.push(this.id);
	});
	idList = ids.join("|");
	return idList;
}

function getFF(ev){
	//get updated FF based on query
	// get handle to scrollable api 
	var api = $("div.scrollable").scrollable({api:true});
	idList = getClickedIDs();
	//alert(idList);
	q = $("#query").attr("value");
	getFFParams="";
	if(idList!="" && q==""){
		//search category only
		getFFParams = ev+"/category/"+idList;		
	}
	if(q!="" && idList==""){
		//search keyword only
		getFFParams = ev+"/keyword/"+q;
	}
	if(q!="" && idList!=""){
		//search both only
		getFFParams = ev+"/cat^key/"+q+"^"+idList;
	}
	//alert(getFFParams);
	if(getFFParams!=""){
		$.ajax({ 
			url: "/getff/"+getFFParams,
			dataType: "json",
			success: function(data){
				if(data.length!=0){
					var noresults = false;
					putFFsOnPage(data,noresults);
				}
				else{
					$.ajax({ 
						url: "/getff/"+ev+"/recent",
						dataType: "json",
						success: function(data){
							if(data.length!=0){
								var noresults = true;
								putFFsOnPage(data,noresults);
							}
						}
					});
				}
			}
		});		
	}
	else{
		for($i=0;$i<=api.getItems().length;$i++){
			// remove last item by using jQuery's remove() method 
		    api.getItems().remove();
		}
		//document.fileGen.fastfacts.value=FFList;
	}	
	// rebuild scrollable and move to the end to see what happened   
	api.reload();
	return false;
}

function getStory(ev,id){
	ev = ev.toLowerCase();
	getFFParams = ev+"/story/"+id;
	//alert(getFFParams);
	var api = $("div.scrollable").scrollable({api:true});
	if(getFFParams!=""){
		$.ajax({ 
			url: "/getstory/"+getFFParams,
			dataType: "json",
			success: function(data){
				if(data.length!=0){
					var noresults = false;
					putFFsOnPage(data,noresults);
				}
			}
		});
	}
	else{
		for($i=0;$i<=api.getItems().length;$i++){
			// remove last item by using jQuery's remove() method 
		    api.getItems().remove();
		}
		//document.fileGen.fastfacts.value=FFList;
	}
	// rebuild scrollable and move to the end to see what happened
	api.reload();
	
	//send FFArr to a timeout script to trigger the autoplay
	//autoscroller = setInterval('autoAdvanceScroller(FFsArr)',10000);
	return false;
}

function autoAdvanceScroller(FFsArr){
	FF = FFsArr[storyItem];
	FFArr = FF.split("^");
    clickThumb(FFArr[2],FFArr[1],FFArr[0],true,true);	
	var api = $("div.scrollable").scrollable({api: true}); 
	api.click(storyItem);
	storyItem = storyItem+1;
	if(storyItem>=FFsArr.length){
		storyItem = 0;
	}
}

function putFFsOnPage(ffs,noresults){
	$("#related-FFs").fadeOut();
	var api = $("div.scrollable").scrollable({api:true});
	api.seekTo(0);
	for($i=0;$i<=api.getItems().length;$i++){
		// remove last item by using jQuery's remove() method 
	    api.getItems().remove();
	}
	var firstItem = ffs[0];
	al = "";
	$.each(ffs, function(i,f) {
		// append new item using jQuery's append() method
		fn = f.name;
		fn = fn.replace(/'/g,"&rsquo;");
		al = al+"|"+fn;
	    api.getItemWrap().append("<div class=\"{id:'"+f.id+"',name:'"+fn+"',filename:'"+trim(f.filename)+"'}\"><img src='/images/FastFacts/Thumbs/"+f.filename.replace(".png",".jpg")+"'></div>");
		api.getItems().bind("click", function(){
			var ffName = $(this).metadata().name;
			var ffID = $(this).metadata().id;
			var ffFilename = $(this).metadata().filename;
			clearInterval(autoscroller);
		    clickThumb(ffFilename,ffName,ffID,true,true);
		});
		api.getItems().bind("mouseenter",function(event){
			var metadata = $(this).metadata();
			var content = '<strong>'+metadata.name+'</strong>';
			var contentchars = content.length;
			tooltipwidth = 5*contentchars + 30;
			$('div#tooltip').hide().find('div.tooltip-content').html(content);
			$("#tooltip").css("width",tooltipwidth + "px");
			tooltipMove(event,"left");
			$('div#tooltip').show();
		});
		api.getItems().bind("mousemove",function(event){
			tooltipMove(event,"left");
		});
		api.getItems().bind("mouseleave",function(){
			$('div#tooltip').hide();
		});
	});
	//alert(al);
	if(!noresults){
		//set the big img to match the first in the scroller
	    //alert(firstItem[2]+"|"+firstItem[1]+"|"+firstItem[0],true);
	    clickThumb(firstItem.filename,firstItem.name,firstItem.id,true,true);
	}
	else{
    	clickThumb("noResults.jpg","","",false);
	}
	//alert($("div.scrollable").html());
}

// execute your scripts when DOM is ready. this is a good habit 
$(function() {
    // initialize scrollable
    	var api = $("div.scrollable").scrollable({
			api: true
		});
		
		//if(eventShortName=='Davos10'){
			var scrnsvr=0;
			scrnsvr = setInterval("displayMode('/coverflow/','"+eventShortName+"',1)",90000);
			$("body").mousemove(function(event){
				clearInterval(scrnsvr);
				scrnsvr = setInterval("displayMode('/coverflow/','"+eventShortName+"',1)",90000);
			});	
		//}

	// select items and do something when they are clicked 
	    $("div.scrollable: div.items div").click(function() { 
			var ffName = $(this).metadata().name;
			var ffID = $(this).metadata().id;
			var ffFilename = $(this).metadata().filename;
			clearInterval(autoscroller);
		    clickThumb(ffFilename,ffName,ffID,true,true);
	    });
	
		$('div.scrollable: div.items div').mouseenter(function(event){
			var metadata = $(this).metadata();
			var content = '<strong>'+metadata.name+'</strong>';
			var contentchars = content.length;
			tooltipwidth = 5*contentchars + 30;
			$('div#tooltip').hide().find('div.tooltip-content').html(content);
			$("#tooltip").css("width",tooltipwidth + "px");
			tooltipMove(event,"left");
			$('div#tooltip').show();
		});
		$('div.scrollable: div.items div').mousemove(function(event){
			tooltipMove(event,"left");
		});
		$('div.scrollable: div.items div').mouseleave(function(){ $('div#tooltip').hide(); });
	
		$("#query").keypress(function(e) {
		    if(e.keyCode == 13) {
				$.tree_reference("treemenu").deselect_all();
				getFF(eventShortName);
			}
		});
		
		$('#bigFFImg').mouseenter(function(event){
			if($(this).parent().attr('id')!=""){
				var content = '<strong>Click for Embed Tag for This Fast Fact</strong>';
				$('div#tooltip').hide().find('div.tooltip-content').html(content);
				tooltipMove(event,"left");
				$("#tooltip").css("width",300);
				$('div#tooltip').show();
			}
		});
		$('#bigFFImg').mousemove(function(event){
			tooltipMove(event,"left");
		});
		$('#bigFFImg').mouseleave(function(){ 
			$('div#tooltip').hide();
		});
		$('#bigFFImg').click(function(event){
			if($(this).parent().attr('id')!=""){
				var content = "<iframe src='"+getBaseURL()+"/syndication/e/image/"+$(this).parent().attr('id')+"' width='440px' height='570px' border='0' scrolling='no'></iframe>";		
				showCoverLayer(content,"img");
				pageTracker._trackEvent("Syndication", "Generate Embed Tag", "image/"+$(this).parent().attr('id'));
			}
		});
		
		$('#EmbedTagLink').click(function(event){
			syndVal = getSyndValues();
			var content = "<iframe src="+getBaseURL()+"/syndication/"+eventShortName+"/"+syndVal+"/  width='440px' height='650px' border='0' scrolling='no'></iframe>";
			showCoverLayer(content,"cat");
			pageTracker._trackEvent("Syndication", "Generate Embed Tag", syndVal);
		});
		$('#rss').click(function(event){
			syndVal = getSyndValues();
			var content = getBaseURL()+"/rss/e/"+syndVal+"/";		
			showCoverLayer(content,"rss");
			pageTracker._trackEvent("Syndication", "RSS Feed", syndVal);
		});
		
		$('#overlay').click(function(event){
			$('#overlay').animate({opacity: '+=0'}, 3000).fadeOut();
		});
		$('#overlay').mouseleave(function(event){
			$('#overlay').fadeOut();
		});
		$('#fileGen img').mouseenter(function(event){
			$(this).fadeTo(25,0.75);
		});
		$('#fileGen img').mouseleave(function(event){
			$(this).fadeTo(25,1);
		});
		$('#addthis').mouseenter(function(event){
			syndVal = getSyndValues();
			return addthis_open(this, '', getBaseURL()+'/'+eventShortName+'/'+syndVal+'/', '[TITLE]');		
			//return addthis_open(this, '', getBaseURL(), 'KnowledgeConcierge - Fast Facts');
		});
		$('#addthis').mouseleave(function(event){
			addthis_close();
		});
		$('#addthis').click(function(event){
			syndVal = getSyndValues();
			pageTracker._trackEvent("Syndication", "AddThis", syndVal);
			return addthis_sendto();
		});	
		$('#constants img').mouseenter(function(event){
			switch(this.id){
				case "EmbedTagLink": var content = 'Embed Tag for this collection of FastFacts'; break;
				case "rss": var content = 'RSS feed for this collection of FastFacts'; break;
				case "pdf": var content = 'PDF with this collection of FastFacts'; break;
				case "ppt": var content = 'PowerPoint with this collection of FastFacts'; break;
			}
			var contentchars = content.length;
			tooltipwidth = 6*contentchars + 50;
			$('div#tooltip').hide().find('div.tooltip-content').html('<strong>'+content+'</strong>');
			$("#tooltip").css("width",tooltipwidth + "px");
			tooltipMove(event,"right");
			$('div#tooltip').show();
		});
		$('#constants img').mousemove(function(event){
			tooltipMove(event,"right");
		});
		$('#constants img').mouseleave(function(){ 
			$('div#tooltip').hide();
		});
		$('.nav_butt').mouseenter(function(event){
			$(this).fadeTo(25,0.75);
		});
		$('.nav_butt').mouseleave(function(event){
			$(this).fadeTo(25,1);
		});
		$('#FFIndex img').mouseenter(function(event){
			if($(this).attr('title')!=""){
				content = "<strong>"+$(this).attr('title')+"</strong>";
				$('div#tooltip').hide().find('div.tooltip-content').html(content);
				tooltipMove(event,"left");
				$("#tooltip").css("width",400);
				$('div#tooltip').show();
			}
		});
		$('#FFIndex img').mousemove(function(event){
			tooltipMove(event,"left");
		});
		$('#FFIndex img').mouseleave(function(){ 
			$('div#tooltip').hide();
		});
		$("#nav_butts img").mouseenter(function(event){
			replImg = $(this).attr("src").replace(".gif","_on.gif");
			$(this).attr("src",replImg);
		});
		$("#nav_butts img").mouseleave(function(event){
			replImg = $(this).attr("src").replace("_on.gif",".gif");
			$(this).attr("src",replImg);
		});
		$('#eventHomePageLinks img').mouseenter(function(event){
			replImg = $(this).attr("src").replace(".png","_on.png");
			$(this).attr("src",replImg);
		});
		$('#eventHomePageLinks img').mouseleave(function(event){
			replImg = $(this).attr("src").replace("_on.png",".png");
			$(this).attr("src",replImg);
		});
		
});

function getSyndValues(){
	syndValues="";
	clickedIDs = getClickedIDs();
	if(clickedIDs){
		if(clickedIDs.indexOf("story_")>-1){
			//this is a story mode click
			//alert("story");
			clickedIDs = clickedIDs.replace("story_","");
			syndValues = "getstory/"+clickedIDs;
		}
		else{
			//it's a regular menu click (category)
			syndValues="category/"+clickedIDs;
		}
	}
	if($("#query").attr("value")!=""){
		syndValues="keyword/"+$("#query").attr("value");
	}
	if(syndValues==""){
		//we have no clicked categories or keyword searches - this must be an image page
		pos = window.location.pathname.indexOf("/image/");
		if(pos>0){
			syndValues = "image/"+$("#bigFFImg").parent().attr('id')
		}
	}
	return syndValues;
}

function showCoverLayer(c,t){
	ht=0;
	if(t=="img"){
		msg = "<P>Copy the text below and paste it on your own website to embed this Fast Fact.<br><br></P>";
		msg = msg+"<textarea name=EmbedInput id=EmbedInput>"+c+"</textarea>";
		ht = 456;
	}
	if(t=="cat"){
		msg = "<P>Copy the text below and paste it on your own website to embed this collection of Fast Facts.<br>The collection will be updated automatically as changes are made.</P>";
		msg = msg+"<textarea name=EmbedInput id=EmbedInput>"+c+"</textarea>";
		ht = 630;
	}
	if(t=="filegen"){
		msg = "<P>Your "+c+" file is being created.<br><br></P>";
		ht = 630;
	}
	if(t=="rss"){
		msg = "<P>Use this URL to access an RSS feed to these FastFacts.<br><br></P>";
		msg = msg+"<textarea name=EmbedInput id=EmbedInput>"+c+"</textarea>";
		ht = 630;
	}
	$('#overlay').fadeOut();
	$('#overlay div').html(msg);
	$('#overlay').css("height",ht);
	$('#overlay').fadeIn();
	$("#EmbedInput").focus();
	$("#EmbedInput").select();
}

function getBaseURL()
{
        // Get document base path
        //documentBasePath = document.location.href;
		documentBasePath = "http://"+window.location.hostname;
		if(window.location.port==10088){
			documentBasePath = documentBasePath+":"+window.location.port;			
		}
		/*documentBasePath = documentBasePath+window.location.pathname;
		//alert(documentBasePath);
        if (documentBasePath.indexOf('?') != -1){
			documentBasePath = documentBasePath.substring(0, documentBasePath.indexOf('?'));
		}
        //documentBasePath = documentBasePath.substring(0, documentBasePath.lastIndexOf('/'));
        documentBasePath = documentBasePath.substring(0, documentBasePath.indexOf('/'));
		*/
		return( documentBasePath );
}

function linkTo(url,action,wind){
	pageTracker._trackEvent("KC Link", action, url);
	if(wind=='new'){
		window.open(url,"_blank");		
	}
	else{
		location.href = url;
	}
}

function clickThumb(f,n,id,c,vb){
	//f=filename, n=name, id=id, c = show constants bool, show visual browser button bool
	
	$("#scrollable-box").show();
	//alert(f+"|"+n+"|"+id+c);
	if(c){ $("#constants").fadeIn(); }
	//show the button to be able ot view ffs in visual browser
	if($("#visual_view").is(":visible")==false && vb){
		$("#visual_view").slideDown(1000);
	}
	$('#bigFFImg').parent().attr("id",id);
	$('#bigFFImg').parent().attr("filename",f);
	f=f.replace(".png",".jpg");
	if(f!="noResults.jpg"){
		f="/images/FastFacts/Big/"+f;
	}
	else{
		f="/images/"+f;
	}
	$("#eventHomePageLinks").hide();
	$("#bigFFImg img").hide();
	//alert(f);
	$("#homePageWrapper").show();
	$("#bigFFImg img").attr("src",f).fadeIn(250);
	if(pageTracker){pageTracker._trackEvent("Fast Fact", "View Image", n);}
}

//Tooltips
function tooltipMove(event,orient)
{
	var offset = $(event.target).offset();
	if(orient == "left"){
		offset.left = event.pageX - 14;
		offset.top = event.pageY + 16;
		$('div#tooltip').css(offset);
		$('#tooltip div.tooltip-tail').css("left",10);
	}	
	if(orient == "right"){
		offset.left = event.pageX - tooltipwidth + 95;
		offset.top = event.pageY + 16;
		$('div#tooltip').css(offset);
		$('#tooltip div.tooltip-tail').css("left",tooltipwidth - 100);
	}
}


function trim(stringToTrim) {			
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
var menuState = null;
function toggleMenu(){
	if(menuState == null || menuState == "closed"){
		$.tree_reference("treemenu").open_all();		
		menuState = "open";
		$("#openClose").attr("src","images/btn_close.png");
	}
	else{
		$.tree_reference("treemenu").close_all();		
		menuState = "closed";
		$("#openClose").attr("src","images/btn_expand.png");
	}	
	pageTracker._trackEvent("Expand Menu", menuState,"");
}
function deselectMenu(){
	$.tree_reference("treemenu").deselect_all();
}
function displayMode(mode,e,scrnsvr){
	//alert(e+"|"+getFFParams+"|"+getFFParams.indexOf("//"));
	if(scrnsvr==1){scrnsvr = "/1";}else{scrnsvr="";}
	if(getFFParams.indexOf("//")==-1 && getFFParams == ""){
		location.href= mode+e+scrnsvr;
	}
	else if(getFFParams != "" && getFFParams.indexOf("//")==-1){
		location.href= mode+getFFParams+scrnsvr;
	}
	else{
		location.href= mode+e+scrnsvr;
	}
}

function createFile(type,event){
	t="";
	$("#fastFactsScroller div").each(function(){
		t=t+$(this).metadata().filename+"|";
	});
	t=t.substring(0,t.length-1);
	document.fileGen.ffList.value=t;
	if(type=='pdf'){doc="PDF";}
	if(type=='ppt'){doc="PowerPoint";}
	if(trim(t)!=""){
		showCoverLayer(doc,'filegen');
		$('#overlay').animate({opacity: '+=0'}, 3000).fadeOut();
		if(event!='e'){document.fileGen.action=getBaseURL()+"/"+type+"/"+event;}
		else{document.fileGen.action=getBaseURL()+"/"+type;}
		pageTracker._trackEvent("Fast Fact", "Create "+type,"");
		document.fileGen.submit();
	}
}

var addthis_config = {
          services_compact: 'email, facebook, twitter, bitly, blogger, buzz, delicious, digg, google, hellotxt, linkedin, pingfm, plurk, posterous, reddit, slashdot, squidoo, stumbleupon, technorati, tumblr, wordpress, yammer',
          services_exclude: 'print'
}
