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="";
	var query = "";
	if(idList!="" && q==""){
		//search category only
		type = "category";	
		query = idList;
	}
	if(q!="" && idList==""){
		//search keyword only
		type = "keyword";	
		query = q;
	}
	if(q!="" && idList!=""){
		//search both only
		type = "cat^key";	
		query = q+"^"+idList;
		getFFParams = ev+"/"+type+"/"+q+"^"+idList;
	}	
	getFFParams = ev+"/"+type+"/"+query;
	
	//for generating files
	document.fileGen.currentQuery.value=type+"/"+query;
	
	//alert(getFFParams);
	if(getFFParams!=""){
		$.ajax({ 
			url: "/getff/"+getFFParams,
			dataType: "json",
			success: function(data){
				if(data.length!=0){
					//alert("have data");
					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();
		}
	}	
	// 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();
		}
	}
	// 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,1);	
	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,1);
	});
	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,1);
	}
	else{
    	clickThumb("noResults.jpg","","",0);
	}
	//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(window.location.port == "" || window.location.port==null || typeof(window.location.port) == "undefined"){

			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,0);
	    });
	
		$('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);
			}
		});
		
		$('#fileGen img').mouseenter(function(event){
			$(this).fadeTo(25,0.75);
		});
		$('#fileGen img').mouseleave(function(event){
			$(this).fadeTo(25,1);
		});

		$('#constants img').mouseenter(function(event){
			var content = "";
			switch(this.id){
				case "EmbedTagLink":
					set_link = getBaseURL()+"/syndication/"+eventShortName+"/"+getSyndValues(0);
					single_link = getBaseURL()+"/syndication/"+eventShortName+"/"+getSyndValues(1);
					all_link = getBaseURL()+"/syndication/"+eventShortName+"/all";
					content = '<h2>Embed Code</h2><p>Select a single fast fact or the set, then copy the code in the box below.</p><select id="embed_selection" onchange="$(\'#embed_text\').val(this.value);$(\'#embed_text\').focus();$(\'#embed_text\').select();"><option value="'+set_link+'" selected="selected">Complete FastFact Set</option><option value="'+single_link+'">Single FastFact</option>';
					if(eventShortName!='all' && eventShortName!='none'){
						content += '<option value="'+all_link+'">All Event Fast Facts</option>';
					}
					content += '</select><input type="text" id="embed_text" name="embed_text" value="'+set_link+'" />';
					$("#tooltip-constant").css("width","100px");
					tooltipleft = "270px";
					break;
				case "pdf": 
					content = '<h2>PDF</h2><p>Select a single fast fact or the set, then click "Download PDF".</p><select id="pdf_selection" onchange="$(\'#embed_text\').val(this.value);"><option value="set" selected="selected">Complete FastFact Set</option><option value="single">Single FastFact</option>';
					if(eventShortName!='all' && eventShortName!='none'){
						content += '<option value="all">All Event Fast Facts</option>';
					}
					content += '</select><input type="image" value="button" id="pdf_button" onClick="createFile(\'pdf\',$(\'#pdf_selection\').val())" name="pdf_button" src="/images/constants_button_pdf.png" />';
					$("#tooltip-constant").css("width","100px");
					tooltipleft = "320px";
					break;
				case "ppt": 
					content = '<h2>Powerpoint</h2><p>Select a single fast fact or the set, then click "Download Powerpoint File".</p><select id="ppt_selection" onchange="$(\'#embed_text\').val(this.value);"><option value="set" selected="selected">Complete FastFact Set</option><option value="single">Single FastFact</option>';
					if(eventShortName!='all' && eventShortName!='none'){
						content += '<option value="all">All Event Fast Facts</option>';
					}
					content += '</select><input type="image" value="button" id="powerpoint_button" onClick="createFile(\'ppt\',$(\'#ppt_selection\').val())" name="powerpoint_button" src="/images/constants_button_powerpoint.png" />';
					$("#tooltip-constant").css("width","100px");
					tooltipleft = "368px";
					break;
				case "addthis_constant_img": 
					set_share_url = getBaseURL()+'/'+eventShortName+'/'+getSyndValues(0)+'/';
					single_share_url = getBaseURL()+'/'+eventShortName+'/'+getSyndValues(1)+'/';
					all_share_url = getBaseURL()+'/'+eventShortName;
					content = '<h2>Share</h2><p>Select a single fast fact or the set, then click "Share".</p><select id="share_selection" onchange="$(\'#embed_text\').val(this.value);"><option value="'+set_share_url+'" selected="selected">Complete FastFact Set</option><option value="'+single_share_url+'">Single FastFact</option>';
					if(eventShortName!='all' && eventShortName!='none'){
						content += '<option value="'+all_share_url+'">Single FastFact</option>';
					}
					content += '</select><img id="addthis" name="addthis" src="/images/constants_button_share.png" onClick="return addthis_open(this, \'\', $(\'#share_selection\').val(), \'[TITLE]\')"/>';
					
					$("#tooltip-constant").css("width","100px");
					tooltipleft = "411px";
					break;
				case "rss": 
					url = getBaseURL()+'/rss/'+eventShortName+'/'+getSyndValues(0)+'/';
					content = '<h2>RSS Feed</h2><p>Copy the RSS feed URL in the box below, then paste the code into your RSS reader to subscribe to this Fast Fact Set.</p><input type="text" id="rss_text" name="rss_text" value="'+url+'" />';
					$("#tooltip-constant").css("width","100px");
					tooltipleft = "465px";
					break;
			}
			
			$('div#tooltip-constant').hide().find('div.tooltip-constant-content').html('<div class="constant_content">'+content+'</div><div class="constant_close_button"><a href="#" onclick="$(\'div#tooltip-constant\').hide();"><img src="/images/constants_button_close.png" border="0" /></a></div>');
                      $('div#tooltip-constant').css({"position":"absolute","top":"65px","margin-left":tooltipleft}).show();
			if(this.id == 'EmbedTagLink'){
			    $("#embed_text").focus();
			    $("#embed_text").select();
			}
			if(this.id == 'rss'){
			    $("#rss_text").focus();
			    $("#rss_text").select();
			}
		});
		
		$('div.span-33').mouseenter(function(){
		    $('div#tooltip-constant').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(single){
	syndValues="";
	clickedIDs = getClickedIDs();
	if(clickedIDs){
		if(clickedIDs.indexOf("story_")>-1){
			//this is a story mode click
			clickedIDs = clickedIDs.replace("story_","");
			syndValues = "getstory/"+clickedIDs;
		}
		else{
			//it's a regular menu click (category)
			syndValues="category/"+clickedIDs;
		}
	}else{
		//this must be a home page - no clicks yet!
		syndValues="/"+eventShortName;
	}
	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');
		}
	}
	if(single){
		//we only want the current image
		syndValues = "image/"+$("#bigFFImg").parent().attr('id');
	}
	return syndValues;
}

function showCoverLayer(c,t){
	ht=0;
	if(t=="filegen"){
		msg = "<P>Your "+c+" file is being created.<br><br></P>";
		ht = 630;
	}
	$('#overlay').fadeOut();
	$('#overlay div').html(msg);
	$('#overlay').css("height",ht);
	$('#overlay').fadeIn();
}

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,advance){
	//f=filename, n=name, id=id, c = show constants bool, show visual browser button bool
	var api = $("div.scrollable").scrollable({api:true});
	
	$("#loading").fadeIn();
	
	$("#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){
		
		//alert(navigator.appName + "|" + navigator.appVersion);
		b = navigator.appVersion;
		//alert(b.indexOf("MSIE 6."));
		if(b.indexOf('MSIE 6.')>0 || b.indexOf('MSIE 7.')>0){
			$showCoverflowButton = false;
		}else{$showCoverflowButton = true;}

		if($showCoverflowButton==true){
			$("#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;
	}
	//f="http://knowledgeconcierge.com"+f;
	$("#eventHomePageLinks").hide();
	$("#bigFFImg img").hide();
	//alert(f);
	$("#homePageWrapper").show();
	
	$('#bigFFImg img').attr('src', f).hide().load(function(){
		$("#loading").fadeOut();
		$(this).fadeIn(250)
	});
	if(advance!=0){
		api.move(advance);		
	}
	document.fileGen.currentImage.value=id;
	if(pageTracker){pageTracker._trackEvent("Fast Fact", "View Image", n);}

}

// Non-Constant 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);
	}
}

// Constant Tooltips
function tooltipConstantMove(event,orient)
{
	var offset = $(event.target).offset();
	if(orient == "left"){
		offset.left = event.pageX - 14;
		offset.top = event.pageY + 16;
		$('div#tooltip-constant').css(offset);
		$('#tooltip-constant div.tooltip-constant-content').css("left",10);
	}
	if(orient == "right"){
		offset.left = event.pageX - tooltipwidth + 95;
		offset.top = event.pageY + 16;
		$('div#tooltip-constant').css(offset);
		$('#tooltip-constant div.tooltip-constant-content').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,setOrSingle){
		if(type=='pdf'){doc="PDF";}
		if(type=='ppt'){doc="PowerPoint";}
		switch(setOrSingle){
			case "single":
				document.fileGen.action = "/"+type+"/"+eventShortName+"/image/"+document.fileGen.currentImage.value;pageTracker._trackEvent("Fast Fact", "Create "+type,"");
				doIt = true;
				break;
			case "set":
				if(document.fileGen.currentQuery.value=='default/recent'){
					alert("Select a set of FastFacts from the left-hand menu to generate a PDF or PowerPoint document. Or create a PDF or PPT from a single FastFact below. We cannot generate a PDF or PPT from this randomized set of images.");
				}
				else{
					document.fileGen.action = "/"+type+"/"+eventShortName+"/"+document.fileGen.currentQuery.value;
					doIt = true;
				}
				break;
			case "all":
				document.fileGen.action = "/"+type+"/"+eventShortName+"/all";
				doIt = true;
				break;
		}

		
		if(doIt == true){
			showCoverLayer(doc,'filegen');
			$('#overlay').animate({opacity: '+=0'}, 3000).fadeOut();
			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'
}

function changeLang(l,e,r){
	//l=lang, e=event, r=redirect
	if(r=='y'){
		//just redirect the page
		if(e.toLowerCase()=='amnc11'){
			e = 'amnc11_cn';
		}
		else{
			e = 'amnc11';
		}
		location.href='/'+e;
	}
	else{
		//display the right button
		$("#btn_lang").css('background-image', 'url(/images/btn_'+l+'.png)');
		$("#lang_view").slideDown(1000);	
	}
}
