/**
*
*
*
**/
var intransition =
	start_sound = 
	this_play = 
	mouse_down = 
	tool_over = 
	timer =
	lastT = 
	viewport_threshold = false;


var cycleTimeout = new Array();
var cyclePause = new Array();
var cycleComplete = new Array();

if(typeof(CARGO) === 'undefined') {
var CARGO = {
	// To use for global variables CARGO.Config.get('dispatch_url')
	Config: {
		'dispatch_url'				: 'dispatch.php',
		'dispatch_prefix'			: 'dispatch/',
		'custom_thumbsize_path'		: '/dispatch/user/saveCustomThumbPosition',
		'drag_drop_options'			: '/dispatch/user/saveDragDropOptions',
		'get_drag_drop_options'		: '/dispatch/user/getDragDropOptions',
		'save_edit_frame'			: '/dispatch/admin/saveEditContent_',
		'save_syntax_color'			: '/dispatch/admin/toggleSyntaxColor',
		'MAX_COMMENT_IMAGES'		: 10,
		'CARGO_CDN'                 : 'http://payload0.cargocollective.com/',
		
		'get': function(key, def) {
				return this[key] ? this[key] : def;
			},
		'getDomain': function() {
           		return "http://"+location.hostname+"/";
			}
	},
	
	// Helper class for getting dispatch urls
	Dispatcher: {
		// Path should be 'c/a'
		'GetUrl': function(path, g) {
			if(typeof(g) == 'array' && g.length > 0) {
				path += '/' + g.split('/');
			}
			return CARGO.Config.getDomain() + CARGO.Config.get('dispatch_prefix') + path;
		}
    },

	// Use this to get absolute paths
	'GetPathAbs': function(path_rel) {
		return CARGO.Config.getDomain() + path_rel;
	},
	
	// A lazy loader of sorts
	'loaded_scripts': [],
	'require_once': function(url) {
		url = url.toLowerCase();
		// Check if its in our array
		if(jQuery.inArray(url, this.loaded_scripts) >= 0) {
			return;
		}
		// Check if its in the head (ie not loaded with this script)
		var already_loaded = false;
		$('script').each(function() {
			var src = $(this).attr('src');
		    if(src) {
				src = src.toLowerCase();
		        if(src.search(url) >= 0) {
					CARGO.loaded_scripts.push(url);
					already_loaded = true;
					return false;
				}
		    }
		});
		// load it
		if(already_loaded == false) {
			addScript(url);
			this.loaded_scripts.push(url);
		}
		return;
	}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).ready(function() {
	FollowingSniff();
	if($("body.blog").length > 0) {
		checkForSlideshow();
	}
});
/////////////////////////////////////////////////////////////////////////////////////////////////
function loadHistory() {
	$(".nohover").each(function() {
		if($("#is_domain").val() != "false") {
			$(this).attr("href","#"+$(this).attr("id").replace("p","")+"/"+$(this).attr("title").replace(/ /g, "-"));
		} else {
			$(this).attr("href",$("#url").val()+"#"+$(this).attr("id").replace("p","")+"/"+$(this).attr("title").replace(/ /g, "-"));
		}
		$(this).removeAttr("title");
	});
	
	if($(".search_results").length == 0 && ($("#maincontainer").length > 0 || $("#items_container").length > 0)) {
		$.history.init(openThisPr);
		
		$("a[rel='history']").click(function(){
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			$.history.load(hash);
			return false;
		});
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function hideContextMenu() {
	$("#toolset_admin").removeClass("toolset_active");
	$("#toolset_menu").hide();

	toolsetToggle("on");
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function showContextMenu(which) {
	var toolset_top = $("#toolset").css("top");
	var toolset_right = $("#toolset").css("right");	
	$("#toolset_menu").css({"top" : toolset_top , "right" : toolset_right});
	$("#toolset_admin").addClass("toolset_active");
	$("#toolset_menu").show();
	$("#css_inspector_trigger").click(function() {
		loadCSSInspector();
		return false;
	});
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function loadCSSInspector() {
	if($("#css_inspector").length > 0) {
		// inspector is loaded
		
	} else {
		addScript("/_js/jquery-ui-1.8.14.min.js");
		addScript("/_js/jquery.mini.colors.js");
		addScript("/_js/codemirror-2.15/codemirror-package.js");
		addCSS("/_css/css.inspector.css");
		$.post(CARGO.Dispatcher.GetUrl("admin/cssInspector/"+$("#url").val()), { }, 
		function(data) {
			var jdata = $.parseJSON(data.jdata);
			$.getScript("/_js/cargo.css.inspector.js", function() {
				CSS.Classes.SetAll(jdata.css_data); 	// Load the CSS data
				$("body").append(data.html); 			// append the inspector
				CSS.Inspector.init();					// Initialize
			});
			
		}, 
		"json");
	
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function toolsetToggle(which) {
	if (which == "on") {
		if ($("#toolset_admin a").length > 0 && $("#toolset_admin a").attr("rel").length > 0) {
			$("#toolset_admin a").attr("href",$("#toolset_admin a").attr("rel")).removeAttr("rel");
		}
	} else if (which == "off") {
		if ($("#toolset_admin a").length > 0 && $("#toolset_admin a").attr("href").length > 0 && tool_over && mouse_down) {
			$("#toolset_admin a").attr("rel",$("#toolset_admin a").attr("href")).removeAttr("href");
			mouse_down = false;
			showContextMenu();
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("initToolset", function(e) {
	if($("#toolset").length > 0) {
		$("#toolset_admin").mousedown(function(e) {
			mouse_down = true;
			if(e.button == 2){
				showContextMenu();
			} else{
				setTimeout("toolsetToggle('off')", 500);
			}
			
		}).mouseup(function() {
			mouse_down = false;
			
		}).mouseover(function() { 
			tool_over = true;
			
		}).mouseout(function() {
			tool_over = false;
		
		}).click(function() { 
			if ($("#toolset_admin a").attr("href").length > 0 && tool_over) {
				document.location.href = $("#toolset_admin a").attr("href");
				hideContextMenu();
			}
			return false;
		});
		
		$("#toolset_admin").bind("contextmenu", function(e) {
			return false;
		});
		
		$(document).click(function() { 
			if(!mouse_down && !tool_over){
				hideContextMenu();
			}
	
		}).mouseup(function(e) { 
			if(e.button == 2){
				mouse_down = false;
			}
			setTimeout("toolsetToggle('on')", 100);
		});
		
		$("#toolset_menu a").bind("click mouseup mouseover", function(e) {
			if(e.type == "mouseover") {
				toolsetToggle("on");
			} else {
				// window.location.href = $(this).attr("href");
				hideContextMenu();
			}
		});
		
		$("#toolset_admin a").click(function(e) {
			if(e.ctrlKey) { 
				showContextMenu();
				return false;
			}
		});
		
		$(document).bind("projectIndex", function(e, pid){
			hideContextMenu();
		});
		
		$("#toolset_menu a:first").addClass("toolset_first");
		$("#toolset_menu a:last").addClass("toolset_last");
		
		$("#toolset_network_leave").click(function() { 
			if(confirm("Leave this network?")) return true;
			else return false;
		});
		
		$("#toolset_network_join").click(function() { 
			if(confirm("Join this network?")) return true;
			else return false;
		});
	}
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("networkFilterMenu", function(e) {
	var networkFilterVisible = 0;
	
	$(".network_filter_menu a:first").addClass("network_filter_menu_first");
	$(".network_filter_menu a:last").addClass("network_filter_menu_last");
	
	$(".show_network_menu").click(function() {
		networkFilterVisible = 1;
		$(".network_filter_menu").show();
	});
		
	$(document).click(function() { 
		if(networkFilterVisible == 1){
			networkFilterVisible = 0;
		} else {
			$(".network_filter_menu").hide();
		}
	});
});
/////////////////////////////////////////////////////////////////////////////////////////////////
function hideNetworkFilterMenu() {
	var networkFilterVisible = 0;
	$(".network_filter_menu").hide();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("projectLoadStart", function(e) {
	/* Close toolset menu */
	hideContextMenu();
	hideNetworkFilterMenu();
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("pageReady", function(e, history_type) {
	if(history_type == "follow")  followLoadHistory();
	else if(history_type != "none") loadHistory();
	$(document).trigger("projectReady", ["first"]);
	$(document).trigger("loadSearch");
	$(document).trigger("initToolset");
	$(document).trigger("networkFilterMenu");
	$(document).trigger("keyboardShortcuts");
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("keyboardShortcuts", function(e, which) {
	var me = (location.host.indexOf("cargocollective.com") >= 0) ? "http://"+location.host+"/"+$("#url").val() : "http://"+location.host;
	
	shortcut.add("H",function() { if($(window).scrollTop() > 50) { window.scrollTo(0, 50); doscroll(0,getScrollHeight(),0);}},{ 'type':'keydown', 'disable_in_input':true, 'keycode':72 });
	if(which != "feed") {
		shortcut.add("J",function() { $(document).trigger("showNextProject"); },{ 'type':'keydown', 'disable_in_input':true, 'keycode':74 });
		shortcut.add("K",function() { $(document).trigger("showPrevProject"); },{ 'type':'keydown', 'disable_in_input':true, 'keycode':75 });
		shortcut.add("R",function() { $(document).trigger("showRandomProject"); },{ 'type':'keydown', 'disable_in_input':true, 'keycode':82 });
		shortcut.add("X",function() { $(document).trigger("closeProject"); },{ 'type':'keydown', 'disable_in_input':true, 'keycode':88 });
		shortcut.add("I",function() { $(document).trigger("closeProject"); },{ 'type':'keydown', 'disable_in_input':true, 'keycode':73 });
	} else {
		shortcut.add("J",function() { $(document).trigger("showNextFeedProject"); },{ 'type':'keydown', 'disable_in_input':true, 'keycode':74 });
		shortcut.add("K",function() { $(document).trigger("showPrevFeedProject"); },{ 'type':'keydown', 'disable_in_input':true, 'keycode':75 });
		shortcut.add("I",function() { top.document.location.href=me+"/index" },{ 'type':'keydown', 'disable_in_input':true, 'keycode':73 });
	}
	
	
	shortcut.add("Shift+F",function() { top.document.location.href=me+"/following" },{ 'type':'keydown', 'disable_in_input':true, 'keycode':70 });
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("projectReady", function(e, dataObj) {	
	checkForSound();
	checkForSlideshow();
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("loadSearch", function(e) {	
	$("#search_form_results, #search_form, #rail_search_form").submit(function(te) {
		$(document).trigger("doSearch", [$(this).attr("id")]);
		return false;
	});
	$("#search_form #search_term, #rail_search_form #search_term").focus(function() {
        if($(this).val() == $(this).attr("rel")) $(this).val("");
    }).blur(function() {
        if($(this).val() == "") $(this).val($(this).attr("rel"));
    }).blur();
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("doSearch", function(e, form) {
	var search_term = $('#'+form+' #search_term').val();
	search_term.replace(" ","-");
	
	if ($("#following_header").length != 0) {
		if(location.host.indexOf("cargocollective.com") >= 0) {
			var loc = document.location.pathname.split("/");
			var url = (loc[0] != "") ? loc[0] : loc[1];
			var me = "http://"+location.host+"/"+url;
		} else {
			var me = "http://"+location.host;
		}
		document.location.href=me+"/following/search/"+search_term;
		
	} else {
		var me = (location.host.indexOf("cargocollective.com") >= 0) ? "http://"+location.host+"/"+$("#url").val() : "http://"+location.host;
		document.location.href=me+"/search/"+search_term;
	}
});
/////////////////////////////////////////////////////////////////////////////////////////////////
function checkForSound() {
	// see if there is a sound && see if soundmanager is loaded
	// Check for firefox
	$(".audio_component .play_pause").live('click', function() { 
		var force = false;
	   if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		  var ffversion=new Number(RegExp.$1); // capture x.x portion and store as a number
		  if(ffversion < 3.6) { force = true; }
	   } //else if($("#template").val() == "SC") { force = true; } // test for SpaceCollective
		
		$(document).trigger("audioPlayPause", [$(this).attr("rel"),$(this).attr("class")]);
		
		if(($(".audio_component").length > 0 || force == true) && $("#soundmanagerJS").length <= 0) {
			$(this).removeClass("play").addClass("pause");
			
			//$('<div id="onscreen_audio" style="position:fixed; top:30px; right:30px; z-index:10000;"></div>').insertBefore("#content_container");
			
			var ui=document.createElement('script');
			ui.id='jQueryUIJS';
			ui.setAttribute('type','text/javascript');
			ui.setAttribute('src','/_js/jquery-ui-1.8.14.min.js');   
	
			var sm=document.createElement('script');
			sm.id='soundmanagerJS';
			sm.setAttribute('type','text/javascript');
			sm.setAttribute('src','/_js/soundmanager/soundmanager2-nodebug-jsmin.js');

	
			var hd=document.getElementsByTagName('head')[0];
			hd.appendChild(ui);
			hd.appendChild(sm);
		  
			start_sound = $(this).parents(".audio_component").attr("id");
			this_play = $(this);
		}
	});
	
	if(($(".audio_component").length > 0 ) && $("#DroidFont").length <= 0) {
		 // Load the external font from the google api
		  var droidfont=document.createElement('link');
		  droidfont.id='DroidFont';
		  droidfont.setAttribute('type','text/css');
		  droidfont.setAttribute('rel','stylesheet');
		  droidfont.setAttribute('href','http://fonts.googleapis.com/css?family=Droid+Sans+Mono');   
		  
		  var hd=document.getElementsByTagName('head')[0];
		  hd.appendChild(droidfont);
	};
	$(".progress").css("display","none");
	initPlayerSize();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function initPlayerSize() {
	$(".audio_component").each(function(){
		if($(this).width() > 0) {
			// Setup playhead/progress width 
		   //$('.Href', this).hide();            
		   var position = $(".position", this);
		   var playhead = $(".playhead", this);
		   // This makes the player correctly sized based on the .Sound width property
		   var soundWidth = $(this).width();
		   var soundBordersWidth = $(".border", this).outerWidth() - $(".border", this).width();
		   var controlsWidth = $(".controls", this).width(soundWidth - soundBordersWidth).width();
		   var volumeWidth = $(".volume", this).width();
		   var playpauseWidth = $(".play_pause", this).width();
		   var spacerWidths = $(".vertical_border", this).width() * 2;
		   $(".border", this).width(soundWidth - soundBordersWidth);
		   $(".info", this).width(controlsWidth - volumeWidth - playpauseWidth - spacerWidths);
		  
		   var refWidth = $(".info", this).width();
		   position.width(refWidth);
			 
		   playhead
			 .css("width", refWidth+"px")
			 .css("left", 0);
	
		   var progressBordersWidth = $(".progress", this).outerWidth() - $(".progress", this).width();
		   $(".progress")
			 .css("width", (refWidth - progressBordersWidth) +"px")
			 .css("left", 0);
			
			if($("#home_content").length > 0) var prog_left = "35px";
			else var prog_left = "0px";
			
		   $(".progress_clip")
			 .css("position", "absolute")
			 .css("overflow", "hidden")
			 .css("width", refWidth+"px")
			 .css("left", prog_left);
		   
		   $(".position")
			 .css("left", prog_left);
	
		   $(".playhead_container", this)
			 .css("position", "relative")
			 .css("width", (playhead.outerWidth() * 2) + "px")
			 .css("left", ((playhead.outerWidth() * -1)) + "px");
	
		   $(".progress_container", this)
			 .css("position", "absolute")
			 .css("z-index", "-1")
			 .css("width", (playhead.outerWidth() * 2) + "px")
			 .css("left", ((playhead.outerWidth() * -1)) + "px");
		
		} // end width check
	});
	
}

/////////////////////////////////////////////////////////////////////////////////////////////////
function openThisPr(pid) {
	if(pid) {
		var href=pid.split("/");
		var comment_id = false;
		if(href.length > 2 && href[2].indexOf("comment") == 0) {
			comment_id = href[2].replace("comment","");
		}
		var pid = href[0];
		if($("#follow_url").length > 0 && pid == $("#current_open").val()) { 
			// do nothing
		} else {
			$(document).trigger("projectLoadStart", [pid,href]);
			if(document.getElementById('p'+pid)) var url = document.getElementById('p'+pid).name;
			if(url == '' || !url) var url = $("#url").val();
			
			var nurl = $("#url").val();
			var viewtype = $("#viewtype").val();
			var template = $("#template").val();
			var previewtemplate = $("#previewtemplate").val();
			var design = $("#design").val();
			var designpath = $("#designpath").val();
			var templatepath = $("#templatepath").val();
			var spinner = document.getElementById('load_'+pid);
			var nav_spinner = document.getElementById('nav_loadspin');
			if(spinner) spinner.style.display = "block";
			if(nav_spinner && viewtype != "following") nav_spinner.style.display = "block";
			
			if(!isNaN(parseInt(templatepath))) templatepath = designpath.replace("/"+design,"");
			
			var cur = document.getElementById('current_open');	
			var prev = document.getElementById('prev_open');
			var prev_type = document.getElementById('prev_type');
			var this_spot = document.getElementById('this_spot');
			var send_open = true;
	
			$("#prev_open").val($("#current_open").val());
			$("#current_open").val(pid);
			var this_spot = pid_list.indexOf(pid);
			if(!this_spot) this_spot = -1;
			$("#this_spot").val(this_spot);
			
			if(document.getElementById('menu_'+prev.value)) document.getElementById('menu_'+prev.value).className = prev_type.value;
			if(document.getElementById('menu_'+pid)) {
				prev_type.value = document.getElementById('menu_'+pid).className;
				document.getElementById('menu_'+pid).className = "nav_active";	
			}
			
			/// SC
			if($('#items_container').length > 0 && $("#templatepath").val().indexOf("network") < 0) {
				if(pid == $("#prev_open").val()) send_open = false;
				else {
					$("#moduleholder_c").val($("#moduleholder_o").val());
					$("#moduleholder_o").val($("#item_"+pid).html());
					$("#modulenumber").val($("#prev_open").val());
				}
				
				
			}
			
			if(previewtemplate && previewtemplate == "true") {
				var data = {pid: pid, viewtype: viewtype, url: url, design: design, template: template, comment_id: comment_id};
			} else {
				var data = {pid: pid, viewtype: viewtype, url: url, nurl: nurl, comment_id: comment_id };
			}
			
			
			if(send_open) $.post(CARGO.Config.getDomain() + templatepath + "/entry-detail.php", data, openThisPrInline);
			else if(spinner) spinner.style.display = "none";
			
			intransition = true;
			
			if(document.getElementById('item_'+pid)) var thispage = document.getElementById('item_'+pid).getAttribute("page");
			var limit = document.getElementById('limit').value;
			var cur = document.getElementById('current_page').value;
			if(thispage && thispage != 0) {
				if(thispage != cur) {
					changePage(thispage,limit);
					if(document.getElementById('item_'+pid)) {
						var thisspot = document.getElementById('item_'+pid).getAttribute("spot");
						document.getElementById('this_spot').value = thisspot;
					}
				}
			}
			
			// kill slideshow cycles
			for(i=0;i<20;i++) {
				clearTimeout(cycleTimeout[i]);
			}
	    	cycleTimeout = new Array();
			cyclePause = new Array();
			cycleComplete = new Array();

		} // end if !following
	
	} else {
		$("#load").empty();
		var location_str = location+" ";
		if($("#start_page").length > 0 && ($('#prev_open').val() == "none" || location_str.indexOf("#") < 0)) openThisPr($("#start_page").val());
		else closeThisPr($('#current_open').val(),false,'list');
	}
	return false;
}

/////////////////////////////////////////////////////////////////////////////////////////////////
function openThisPrInline(data) {
	var starting = data.indexOf("|#=#|");
	var starting2 = data.indexOf("|##=##|");
	var starting3 = data.indexOf("|###=###|");
	var pid = data.substring(0, starting);
	var slideheight = data.substring((starting+5), starting2);
	var slidecount = data.substring((starting2+7), starting3);
	var content = data.substring((starting3+9), data.length);
	var isIE = testIE();
	
	if($('#maincontainer').length > 0) {
		var container=document.getElementById('maincontainer');
		var prev = document.getElementById('prev_open');
		var prev_type = document.getElementById('prev_type');
		var spinner = document.getElementById('load_'+pid);
		var nav_spinner = document.getElementById('nav_loadspin');
		var o_thumb_nav = document.getElementById('o_thumb_nav').value;
		var current_page = document.getElementById('current_page').value;
		if(spinner) spinner.style.display = "none";
		if(nav_spinner) nav_spinner.style.display = "none";
		
		$(".project_thumb").removeClass("active");
		$("#item_"+pid).addClass("active");
		
	} else if(document.getElementById('items_container')) {
		var prev = $("prev_open").val(); 
		if(prev == pid && document.getElementById('item_'+pid).className == "project_feed_full") container = false;
		//else if(prev != "none" && prev != pid) closeFeedPr(prev,true);
		else {
			var container=document.getElementById('item_'+pid);
			container.onmouseover = "";
			container.onmouseout = "";
			container.className = "project_feed_full";
			if(isIE) $('#item_'+pid).addClass("ie");
			try { DD_roundies.addRule(".project_feed_full", 5, true); } catch(err) { }
			//
			if($("#moduleholder_c").val() != "none") {
				var oldpid = $("#modulenumber").val();
				var closecontent = $("#moduleholder_c").val();
				printClosed(oldpid,closecontent,true);
				oldpid = "none";
				closecontent = "none";
			}
		}
		if(!content || content == "") container = false;
		
		
	} else {
		var container=document.getElementById('pRow'+pid);
		container.className = "content_container_open";
	}
	
	if(container) {
	   // Fire an event before this project gets overwritten
      $(document).trigger("projectClose", [container]);  
	   
		var isIE = testIE();
		container.style.display = "block";
		//container.innerHTML=content;
		if($('#maincontainer').length > 0 && isIE) container.innerHTML=content; 
		else if($('#maincontainer').length > 0) $("#maincontainer").html(content);
		else if($('#pRow'+pid).length > 0) $("#pRow"+pid).html(content);
		else if($('#item_'+pid).length > 0) $("#item_"+pid).html(content);
	}
	
	intransition = false;	
	
	//doscroll(0,getScrollHeight(),0);
	if(!document.getElementById('home_gallery') && !document.getElementById('items_container') && !document.getElementById('no_scroll')) {
		if(getScrollHeight() > 50) window.scrollTo(0, 50);	
		doscroll(0,getScrollHeight(),0);
	}
	
	if(o_thumb_nav == "yes") { 
		$("#page_"+current_page).css("display","none");
	}
	
	// Set the ready return
	var readyObj = Array();
	readyObj["pid"] = pid;
	readyObj["slideheight"] = slideheight;
	
	var isHome = document.getElementById('home_gallery');
	if($('#items_container').length > 0 && $('#items_container.network').length == 0) {
		$(document).trigger("projectReady", [ readyObj ]);
		shiftPosition(true);
		var spacerHeight = $('#item_'+pid).height();
		$('#item_'+pid+" #body_container").before('<div style="height:'+spacerHeight+'px" id="cardspacer">&nbsp;</div>');
		$('#item_'+pid+" #body_container").css("display","none");
		if($(".header_img").css("position") == "fixed") var toppad = $(".header_img").height();
		else var toppad = 60;
		if($('#startpage').val() == 'none' || $('#startpage').val() != pid) {
			$.scrollTo( { top:($('#item_'+pid).offset().top-toppad), left:0}, 450, { onAfter:function(){ 
					$('#cardspacer').remove();
					$('#item_'+pid+" #body_container").fadeIn(); 
					$('#item_'+pid).addClass("open");
					//$(document).trigger("projectReady", [ readyObj ]);
				} 
			}); 
		} else {
			$('#cardspacer').remove();
			$('#item_'+pid+" #body_container").fadeIn(); 
		}
		$('#startpage').val('none');
		$(document).trigger("SCprojectLoadComplete", [ pid ]);
		return false; 
		
		
	} else if(!$("#home_gallery")) {
		if(getScrollHeight() > 50) window.scrollTo(0, 50);	
		doscroll(0,getScrollHeight(),0);
	
	}
	
	// We're ready
	$(document).trigger("projectReady", [ readyObj ]);
	
	if (typeof projectLoadComplete == "function") projectLoadComplete(); // deprecated, but leaving
	$(document).trigger("projectLoadComplete", [ pid ]);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("closeProject", function(e){
	if($("#template").val() == "spacecollective") closeFeedPr($("#current_open").val(),false,'list');
	else closeThisPr($("#current_open").val(),false,'list');
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("initNextProject", function(e){
	$(".project_next a").live("click", function() { 
		if(pr_list.length > 1) $(document).trigger("showNextProject");
		return false;
	});
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("showNextProject", function(e){
	var cur = ($("#current_open").val() != "none") ? $("#current_open").val() : pr_list[pr_list.length-1];
	if($("#prev_open").val() == "none" && cur == $("#start_page").val()) cur = pr_list[pr_list.length-1];
	
	if($("#load_"+cur).css("display") == "block" && ($("#template").val() == "spacecollective" || $("#template").val() == "network")) var fail;
	else {
		var spot = array_search(cur, pr_list);
		if(parseInt(cur) > 0 && spot === false) var next = 0;
		else if(cur == pr_list[pr_list.length-1]) var next = 0;
		else var next = parseInt(spot)+1;
		
		var title = stripslashes(prt_list[next]);
		if(title) title = makeDetailLink(title);
		else title = "";
		$.history.load(pr_list[next]+"/"+title);
	}
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("showPrevProject", function(e){
	var cur = ($("#current_open").val() != "none") ? $("#current_open").val() : pr_list[0];
	if($("#prev_open").val() == "none" && cur == $("#start_page").val()) cur = pr_list[0];
	
	if($("#load_"+cur).css("display") == "block" && ($("#template").val() == "spacecollective" || $("#template").val() == "network")) var fail;
	else {
		var spot = array_search(cur, pr_list);
		if(parseInt(spot) > 0 && spot === false) var next = pr_list.length-1; 
		else if(parseInt(spot) == 0 || parseInt(cur) == 0) var next = pr_list.length-1; 
		else var next = parseInt(spot)-1; 
		
		if(spot === false || next === false) next = pr_list.length-1;
		var title = stripslashes(prt_list[next]);
		if(title) title = makeDetailLink(title);
		else title = "";
		$.history.load(pr_list[next]+"/"+title);
	}
});

/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("showNextFeedProject", function(e){
	var move_speed = 250;
	var padding = viewport_threshold;
	var current = $(".entry:in-viewport").attr("id");
	
	var next_post = (!current) ? "#"+$(".entry:first").nextAll(".entry").attr("id") : "#"+$("#"+current).nextAll(".entry").attr("id");
	if (next_post != "#undefined") {
		var next_offset = $(next_post).offset().top-padding;
	
		clearTimeout(timer);
		window.scrollTo(0, (next_offset-padding)); 
		doscroll(next_offset,$(window).scrollTop(),0);
	
		//$.scrollTo(next_post, move_speed, {offset: {top:-padding}});
		var within_bounds = (($(window).scrollTop()+$(window).height()) >= ($("body").height()-1500)) ? true : false;
		if(next_post == "#"+$(".entry:last").prevAll(".entry").attr("id") && !within_bounds) getMoreHistory();
	}
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("showPrevFeedProject", function(e){
	var move_speed = 250;
	var padding = viewport_threshold;
	var current = "#"+$(".entry:in-viewport").attr("id");
	
	if (current != "#undefined") {
		if($(window).scrollTop() > $(current).offset().top) {
			if(current != "#"+$(".entry:last").attr("id")) current = "#"+$(current).nextAll(".entry").attr("id");
			else current = "."+$(current).next().attr("class");
			
			if(current == ".") current = "#new_page_content";
		}
		
		var prev_post = ($(current).prevAll(".entry").length <= 0) ? "body" : "#"+$(current).prevAll(".entry").attr("id");
		var prev_offset = $(prev_post).offset().top;
		
		clearTimeout(timer);
		window.scrollTo(0, prev_offset); 
		doscroll((prev_offset-padding),$(window).scrollTop(),0);
		//$.scrollTo(prev_post, move_speed, {offset: {top:-padding}});
		
	}
});
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("showRandomProject", function(e){
	var cur = ($("#current_open").val() != "none") ? $("#current_open").val() : false;
	cur = array_search(cur, pr_list);
	var spot = Math.floor(Math.random()*pr_list.length-1);
	if(parseInt(cur) == spot || spot < 0) var next = 0;
	else var next = parseInt(spot);
	
	var title = stripslashes(prt_list[next]);
	if(title) title = makeDetailLink(title);
	else title = "";
	$.history.load(pr_list[next]+"/"+title);
});
/////////////////////////////////////////////////////////////////////////////////////////////////
function makeDetailLink(title) {
	var url = title
		.replace(/^\s+|\s+$/g, "")	
		.replace(/[_|\s]+/g, "-")
		.replace(/[^a-zA-Z0-9-]+/g, "")
		.replace(/[-]+/g, "-")
		.replace(/^-+|-+$/g, "")
		; 
	return url;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function checkForSlideshow() {
	var slide_list = [];
	$(".slideshow_wrapper").each(function() { 
		var new_slide = $(this).attr("class").replace(/slideshow_wrapper/g,"").replace(/_/g,"").replace(/ /,"");
		if(!in_array(new_slide,slide_list)) startSlideshow(new_slide);
	});
}
/////////////////////////////////////////////////////////////////////////////////////////////////

function startSlideshow(pid) {
	var elements = document.getElementsByClassName("slideshow_container_"+pid);
	var template = $("#template").val();
	var design = $("#design").val();
	if(design) {
		var isSC = template.indexOf("spacecollective") >= 0 ? true : false;
		var isOz = design.indexOf("ozfeed") >= 0 ? true : false;
		var isTesla = design.indexOf("tesla") >= 0 ? true : false;
	} else {
		var isSC = false, isOz = false, isTesla = false;
	}
	if(elements) {
		var el_prev = document.getElementsByClassName("slide_prev_"+pid);
		var el_next = document.getElementsByClassName("slide_next_"+pid);
		var el_count = document.getElementsByClassName("slideshow_count_"+pid);
		var el_nav = document.getElementsByClassName("slideshow_nav_"+pid);
		var el_wrapper = document.getElementsByClassName("slideshow_wrapper_"+pid);
		var el_slideclick = document.getElementsByClassName("slideclick_"+pid);
		var el_caption = document.getElementsByClassName("slideshow_caption_"+pid);
		
		
		for(var i = 0;i < elements.length;i++) {
			elements[i].setAttribute('id','slideshow_container_'+pid+'_'+i);
			elements[i].setAttribute('class','slideshow_container');
			if(el_prev[0]) el_prev[i].setAttribute('id','prev_'+pid+'_'+i);
			if(el_next[0]) el_next[i].setAttribute('id','next_'+pid+'_'+i);
			if(el_count[0]) el_count[i].setAttribute('id','slideshow_count_'+pid+'_'+i);
			if(el_count[0]) el_count[i].setAttribute('class','slideshow_count');
			if(el_nav[0]) el_nav[i].setAttribute('id','slideshow_nav_'+pid+'_'+i);
			$('#slideshow_nav_'+pid+'_'+i).removeClass('slideshow_nav_'+pid);
			if(el_wrapper[0]) el_wrapper[i].setAttribute('id','slideshow_wrapper_'+pid+'_'+i);
			if(el_wrapper[0]) el_wrapper[i].setAttribute('class','slideshow_wrapper');
			if(el_slideclick[0]) el_slideclick[i].setAttribute('id','slideclick_'+pid+'_'+i);
			if(el_slideclick[0]) el_slideclick[i].setAttribute('class','slideclick');
			if(el_caption[0]) el_caption[i].setAttribute('id','slideshow_caption_'+pid+'_'+i);
			if(el_caption[0]) el_caption[i].setAttribute('class','slideshow_caption');
			var divs = elements[i].getElementsByTagName("img");
			if(divs[0]) var slideheight = divs[0].height;
			var slidewidth = 0;
			for(var q=0; q<divs.length;q++) {
				if(divs[q] && divs[q].width > slidewidth) slidewidth = divs[q].width;
				else slidewidth = slidewidth;
				if((isSC || isOz || isTesla) && divs[q]) {
					if(divs[q].height > slideheight) slideheight = divs[q].height;
					else slideheight = slideheight;
				}
			}
			$('#slideshow_wrapper_'+pid+'_'+i).css("width",slidewidth+"px");
			
			if(slidewidth > 560){
				$('#slideshow_caption_'+pid+'_'+i).css("width","560px");
			} else {
				$('#slideshow_caption_'+pid+'_'+i).css("width",slidewidth+"px");
			}
			
			$('#slideshow_container_'+pid+'_'+i+' br').each(function() { $(this).remove(); });
			
			if($("slideconfig").attr("has_thumbs") == "yes") {
				var thumb_position = $("slideconfig").attr("thumb_position");
				var nav_position = $("slideconfig").attr("nav_position");
				var has_nav = $("slideconfig").attr("has_textnav");
				
				if(thumb_position == "top") {
					$('#slideshow_wrapper_'+pid+'_'+i).before('<ul class="slideshow_thumbs" id="slideshow_thumbs_'+pid+'_'+i+'">');
				} else if(thumb_position == "bottom") {
					if(nav_position == "bottom" && has_nav == "yes") {
						$('#slideshow_nav_'+pid+'_'+i).before('<ul class="slideshow_thumbs" id="slideshow_thumbs_'+pid+'_'+i+'">');
						$('#slideshow_nav_'+pid+'_'+i).css("clear","both");
					} else {
						$('#slideshow_wrapper_'+pid+'_'+i).after('<ul class="slideshow_thumbs" id="slideshow_thumbs_'+pid+'_'+i+'">');
					}
				}
				
				$('#slideshow_thumbs_'+pid+'_'+i).css("width",slidewidth+"px");
				
				
				
			} else var has_thumbs = "";
			
			if($("slideconfig").attr("is_autoplay") == "yes") var timeout = parseFloat($("slideconfig").attr("auto_delay"))*1000;
			else var timeout = 0;
			var transition = $("slideconfig").attr("transition");
			if(transition == "none") {
				var transition_speed = 1;
				var transition = "fade";
			} else {
				var transition_speed = '2000';
			}
			
			var first = true;
			var nextSlide;
			
			$(document).ready(function() { 
				$('#slideshow_container_'+pid+'_'+i).cycle({
					fx: transition, 
					pager:  '#slideshow_thumbs_'+pid+'_'+i,
					height: slideheight,
					width: slidewidth,
					next:'#next_'+pid+'_'+i,
					prev:'#prev_'+pid+'_'+i,
					contain:'#slideclick_'+pid+'_'+i,
					timeout:  timeout,
					speed: transition_speed,
					this_i: i,
					
					// callback fn that adjusts the slideshow's height 
					before:	function(){ 
						var $sh = $(this).height();
						var delay = $("slideconfig").attr("transition") == "none" ? 10 : 400;
						if($sh > 0 && !isSC && !isOz) $(this).parent().animate({ height: $sh }, delay);
					},
					
					after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
						if(parseInt(nextSlideElement) >= 0) {
							nextSlide = $("#"+$(currSlideElement).parent().attr("id")+" img:nth-child("+parseInt(nextSlideElement)+")");
						} else {
							nextSlide = nextSlideElement;
						}
						
						$(document).trigger("slideshowTransitionFinish", [nextSlide]);
					},
					
					// callback fn that creates a thumbnail to use as pager anchor 
					pagerAnchorBuilder: function(idx, slide) { 
					//return '<li class="slideshow_thumb"><a href="#"><img src="' + getThumbFile(slide.src) + '" /></a></li>'; }
					return '<li class="slideshow_thumb"><a href="#"><img src="' + slide.src + '" /></a></li>'; }
					
				});
			});
			
			if($("slideconfig").attr("count_style") == "parenth" && el_count[0]) var count_nav = '(1 of '+divs.length+')';
			else if($("slideconfig").attr("count_style") == "no_parenth" && el_count[0]) var count_nav = '1 of '+divs.length;
			$('#slideshow_count_'+pid+'_'+i).html(count_nav);
			
			

		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
$(document).bind("slideshowTransitionFinish", function(e, cur){
	var caption = $(cur).attr("caption");
	if(caption !== undefined){
		$(cur).parent().parent().parent().nextAll('.slideshow_caption').html(caption);
	}
	else{
		$(cur).parent().parent().parent().nextAll('.slideshow_caption').html("");
	}			
});
/////////////////////////////////////////////////////////////////////////////////////////////////
function getThumbFile(file_name) {
	var ext = file_name.substr(file_name.lastIndexOf('.'));
	var name = file_name.substring(0, file_name.lastIndexOf('.'));
	return name+"_t"+ext
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function showStartProject(pid) {
	var container=document.getElementById('maincontainer');
	if(container) container.style.display = "block";

	var cur = document.getElementById('current_open');	
	var prev = document.getElementById('prev_open');
	var this_spot = document.getElementById('this_spot');
	var prev_type = document.getElementById('prev_type');
	
	if(this_spot) {
		this_spot.value = pid_list.indexOf(pid);
		if(prev) prev.value = cur.value;
		cur.value = pid;
		
		if(document.getElementById('menu_'+prev.value)) document.getElementById('menu_'+prev.value).className = prev_type.value;
		if(document.getElementById('menu_'+pid) && $("search_results").length < 0) {
			prev_type.value = document.getElementById('menu_'+pid).className;
			document.getElementById('menu_'+pid).className = "nav_active";	
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function closeThisPr(pid,reopen,viewtype) {
	var prev_type = document.getElementById('prev_type');
	if(document.getElementById('menu_'+pid)) document.getElementById('menu_'+pid).className = prev_type.value;
	var container=document.getElementById('maincontainer');
	
	// Fire an event: projectClose
   $(document).trigger("projectClose", [container]);  
   $(document).trigger("projectIndex", [pid]);  
	
	if(container) {
		container.innerHTML = "";
		container.style.display = "none";
	}
	
	//doscroll(0,getScrollHeight(),0);
	
	if(viewtype == 'single') document.getElementById('item_'+pid).style.display = "block";
	
	$.history.load("");
	if (jQuery.browser.safari) window.scrollTo(0,0);
	$(document).trigger("projectCloseUnload", [pid, container]);  
	
	if(document.getElementById('pr_contain_item_'+pid)) document.getElementById('pr_contain_item_'+pid).className = "";
	
	var o_thumb_nav = document.getElementById('o_thumb_nav').value;
	var current_page = document.getElementById('current_page').value;
	if(o_thumb_nav == "yes") { 
		$("#page_"+current_page).css("display","block");
	}
	
	$(".project_thumb").removeClass("active");
	$(document).trigger("projectCloseComplete", [pid, container]);  
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function changePage(newpage,limit) {
	$(document).trigger("pageChange", [newpage]);
	
	var cur = document.getElementById('current_page').value;
	var total_pages = document.getElementById('total_pages').value;
	var current_page = document.getElementById('page_'+cur);
	var current_nav = document.getElementById('nav_page_'+cur);
	var new_page = document.getElementById('page_'+newpage);
	var new_nav = document.getElementById('nav_page_'+newpage);
	var pagination = document.getElementById('pagination');
	var pid = $('#current_open').val();
	var design = $('#design').val();
	var template = $('#template').val();
	
	
	if(document.getElementById('pr_contain_item_'+cur)) document.getElementById('pr_contain_item_'+cur).className = "";
	
	// dump detail
	var container=document.getElementById('maincontainer');
	if(container) {
		container.style.display = "none";
		container.innerHTML = "";
	}
	// dump SC page
	var itemcontainer=document.getElementById('items');
	if(itemcontainer) {
		
		if(pid != "none" && $("#item_"+pid).attr("spot") == 0 && $("#item_"+pid).attr("page") == 0) { // is page
			$("#item_"+pid).html("");
			$("#item_"+pid).attr("className","pagecontainer");
		}
	}
	
	
		
	// reset nav status
	var current_open = document.getElementById('current_open').value;
	if(current_open) {
		var prev_type = document.getElementById('prev_type');
		if(document.getElementById('menu_'+current_open)) document.getElementById('menu_'+current_open).className = prev_type.value;
	}
	
	// dump the old nav
	if(current_nav) current_nav.style.display = "none";
	
	// show the new nav
	if(new_nav) new_nav.style.display = "block";
	
	// dump prev page thumbs
	if(current_page) current_page.style.display = "none";
	
	// change pagination
	var pagout = "";
	if(newpage > 1) {
		if(design.indexOf("kennedy") >= 0) pagout += "&larr; ";
		/* else if(template.indexOf("network") >= 0) pagout += "<span class='left_arrow'>&larr;</span> "; */
		pagout += "<a href=\"javascript:void(0)\" onclick=\"changePage("+(parseInt(newpage)-1)+","+limit+")\" ";
		pagout += "class=\"prev_page\">Prev page</a>";
	}
	
	if(newpage > 1 && newpage < total_pages) {
		if(design.indexOf("kennedy") >= 0) pagout += "&nbsp;<span>("+newpage+" of "+total_pages+")</span>&nbsp;";
		else if(design.indexOf("amsterdam") < 0 && design.indexOf("hegel") < 0 /* && template.indexOf("network") < 0 */) pagout += "<span>&nbsp;/&nbsp;</span>";
	}
	
	if(design.indexOf("amsterdam") >= 0 || design.indexOf("hegel") >= 0 /* || template.indexOf("network") >= 0 */) pagout += "&nbsp;<span>"+newpage+" of "+total_pages+"</span>&nbsp;";
	
	if(newpage < total_pages) {
		pagout += "<a href=\"javascript:void(0)\" onclick=\"changePage("+(parseInt(newpage)+1)+","+limit+")\" ";
		pagout += "class=\"next_page\">Next page</a>";
		if(template.indexOf("kennedy") >= 0) pagout += " &rarr;";
		/* else if(template.indexOf("network") >= 0) pagout += " <span class='right_arrow'>&rarr;</span>"; */
	
	}
	
	if(design.indexOf("kennedy") < 0 /* && template.indexOf("network") < 0 */ && design.indexOf("amsterdam") < 0 && design.indexOf("hegel") < 0) pagout += "&nbsp;<span>("+newpage+" of "+total_pages+")</span>";
	
	if($(".pagination").length > 0) $(".pagination").each(function() { $(this).html(pagout); });
	
	
	// show next page thumbs
	if(new_page) {
		new_page.style.display = "block";
		var itemsList = new_page.childNodes.length;
		for(i=0;i<itemsList;i++) {
			var thisItem = new_page.childNodes[i];
			thisPid = thisItem.getAttribute("name");
			var thumbContainer = $("#cardthumb_"+thisPid);
			if(thumbContainer.length > 0 && thumbContainer.attr("name") != "") {
				//thumbContainer.innerHTML = "<img src=\""+thumbContainer.getAttribute("name")+"\" border=\"0\" />";
				thisW = thumbContainer.attr("width") ? 'width="'+thumbContainer.attr("width")+'"' : "";
				thisH = thumbContainer.attr("height") ? 'height="'+thumbContainer.attr("height")+'"' : "";
				thisImg = thumbContainer.attr("name");
				thumbContainer.html("<img src=\""+thisImg+"\" border=\"0\" "+thisW+" "+thisH+" />");
				thumbContainer.attr("name","");
			}
		}
	}
	
	if(document.getElementById('menu_'+pid)) {
		$("#menu_"+pid).addClass("nav_active");	
	}
	
	// set new page values
	document.getElementById('current_page').value = newpage;
	curspot = cur < newpage ? (cur*limit)-1 : ((newpage-1)*limit)-1;
	document.getElementById('this_spot').value = curspot;
	
	if(document.getElementById('items') && template.indexOf("network") < 0 && design.indexOf("amsterdam") < 0 && design.indexOf("hegel") < 0) shiftPosition(false);
	
	window.scrollTo(0,0);
	
	//changeHorizNav(newpage);
	$(document).trigger("pageChangeComplete", [newpage]);
	
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function changeHorizNav(newpage) {
	// move pages, pagination and following if nav is horiz
	if($(".nav_container").hasClass("horizontal")) {
		if($("#pagination").length > 0) $("#nav_page_"+newpage).append($("#pagination"));
		if($(".nav_follow").length > 0) $("#nav_page_"+newpage).append($(".nav_follow"));
		if(($(".page_link").length > 0 || $(".link_link").length > 0) && $("#sticky_page").val() != "none") {
			if($("#sticky_page").val() == "top") $("#nav_page_"+newpage).prepend($(".page_link")).prepend($(".link_link"));
			else {
				$("#nav_page_"+newpage).append($(".page_link")).append($(".link_link"));
				if($("#pagination").length > 0) $("#nav_page_"+newpage).append($("#pagination"));
				if($(".nav_follow").length > 0) $("#nav_page_"+newpage).append($(".nav_follow"));
			}
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function FollowingSniff() {
	if($("#following_header").length > 0 || $(".follow_container.home").length > 0) {
		callMyFollowList();
		if($(".follow_container.home").length > 0) {
			$(".follow_pagination a").removeAttr("rel").click(function() { 
				changeFollowPage('2');
				return false;
			});
		} else {
			$.history.init(changeFollowPage);
			$("a[rel='history']").click(function(){
				var hash = this.href;
				hash = hash.replace(/^.*#/, '');
				$.history.load(hash);
				return false;
			});
		}
		$(".recent_following_thumb:odd").addClass("even");
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function doFollow(my_url,their_url,type,name,where) {
	if(type == "add") var agree = confirm("Follow "+stripslashes(name)+"?");
	else if(type == "remove") var agree = confirm("Unfollow "+stripslashes(name)+"?");
	if(agree) {
		if(where == 'follow') {
			$("#following_loadspin").show();
		}
		else var bolt = document.getElementById('following_header_bolt');
		var module = $("#module_"+their_url);
		if(bolt) bolt.innerHTML = '<img src="../_gfx/loadingAnim.gif" width="15" height="15">';
		if(module) module.css("display","none");
		var home_class = $("#home_follow_"+their_url).length > 0 ? "homefollow" : "";
		$("#home_follow_"+their_url+", #user_follow_"+their_url).after(
				"<div class='following_load "+home_class+"'><img src='../_gfx/loadingAnim.gif' width='20' height='20'></div>"
			);
		
		var action = CARGO.Dispatcher.GetUrl("user/doFollow");
		//$.post("/includes/following-process.php", { my_url:my_url, their_url:their_url, type:type, name:name, where:where }, followResult);
		$.post(action, { my_url:my_url, their_url:their_url, type:type, name:name, where:where }, followResult);
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function followResult(data) {
	data = $.parseJSON(data);
	var where = data.where;
	var url = data.url;
	var content = data.html;

	var follow_link = content;
	if(where != 'follow') {
		var bolt = document.getElementById('following_header_bolt_'+where);
		var booklink = document.getElementById('following_header_follow_'+where);
	} else {
		////////////////////////
		var bolt = document.getElementById('following_header_bolt');
		var booklink = document.getElementById('following_header_follow');
	}
	if(bolt){
		if(document.getElementById('home_gallery')) bolt.innerHTML = '<img src="../_gfx/sc-bolt.png" width="15" height="15">';
		else bolt.innerHTML = '<img src="../_gfx/sc-bolt-white.png" width="15" height="15">';
	} 
	if(booklink) booklink.innerHTML = follow_link;
	
	if($("#home_gallery").length > 0) {
		$("#home_follow_"+url).html(content);

	} else if(where == "user-follow") {
		$("#user_follow_"+url).html(content);

	} else if(where == "follow") {
		$("#follow_links").html(content);

	}
	$("#following_loadspin").hide();
	$(".following_load").remove();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function callMyFollowList() {
	//var my_list = $.parseJSON(my_json_list);
	$("user_follow").each(function() { 
		var this_uid = $(this).attr("uid");
		var this_url = $(this).attr("url");
		var c_url = $(this).attr("curl");
		var portfolio_name = $(this).attr("portfolio_name");
		var follow_type = $(this).attr("ftype");
		var follow_link = "'"+c_url+"','"+this_url+"','"+follow_type+"','"+portfolio_name+"', 'user-follow'";
		var id_type = ($(".follow_container.home").length > 0) ? "home" : "user";
		var output = '<span id="'+id_type+'_follow_'+this_url+'">';
		
		if(follow_type == "remove" && this_url != c_url) {
			output += '<a class="deleteLink '+id_type+'follow" onmouseup="doFollow('+follow_link+');" href="javascript:void(0)" title="Unfollow">&times;</a>';	
		} else if(this_url != c_url) {
			output += '<a class="addLink '+id_type+'follow" onmouseup="doFollow('+follow_link+');" href="javascript:void(0)" title="Follow">+</a>';
		}
		output += '</span>';
		
		$(this).replaceWith(output);
	});
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function changeFollowPage(newpage) {
	if(newpage) {
		if(newpage.indexOf("page") >= 0) var ishome = false;
		else var ishome = true;
		if(!ishome) newpage=parseInt(newpage.replace("page",""));
		var cur = document.getElementById('current_page').value;
		var limit = parseInt(document.getElementById('total_pages').value);
		var current_page = document.getElementById('page_'+cur);
		var new_page = document.getElementById('page_'+newpage);
		var pagination = document.getElementById('pagination');
		
		// change pagination
		var pagout = "";
		if(!ishome) {
			var prevlink = "#page"+(parseInt(newpage)-1);
			var nextlink = "#page"+(parseInt(newpage)+1);
		} else {
			var prevlink = "javascript:void(0)\" onclick=\"changeFollowPage('"+(parseInt(newpage)-1)+"')";
			var nextlink = "javascript:void(0)\" onclick=\"changeFollowPage('"+(parseInt(newpage)+1)+"')";
		}
		if(newpage > 1) pagout += "<a href=\""+prevlink+"\" rel=\"history\">Prev page</a>";
		if(newpage > 1 && newpage < limit) pagout += "<span>&nbsp;/&nbsp;</span>";
		if(newpage < limit) pagout += "<a href=\""+nextlink+"\" rel=\"history\">Next page</a>";
		pagout += "&nbsp;<span>("+newpage+" of "+limit+")</span>";
		
		if($(".follow_pagination").length > 0) $(".follow_pagination").each(function() { $(this).html(pagout); });
		$("#page_"+newpage+" img").each(function(){ $(this).attr("src",$(this).attr("name")); });
		
		// show next page thumbs
		if(new_page) {
			new_page.style.display = "block";
			current_page.style.display = "none";
		}
		
		// set new page values
		document.getElementById('current_page').value = newpage;
		
		if(!ishome) {
			$("a[rel='history']").click(function(){
				var hash = this.href;
				hash = hash.replace(/^.*#/, '');
				$.history.load(hash);
				return false;
			});
		}
		
		window.scrollTo(0,0);
	}
	
}
/////////////////////////////////////////////////////////////////////////////////////////////////
	function pageload(hash) {
		if(hash) {
			var template = document.getElementById('template').value;
			$.post(CARGO.Config.getDomain() + "/designs/"+template+"/entry-detail.php", { pid: pid, viewtype: 'list', url: url },openThisPrInline);
		} else {
			$("#load").empty();
		}
	}
/////////////////////////////////////////////////////////////////////////////////////////////////





document.getElementsByClassName = function(clsName){

	var retVal = new Array();
	var elements = document.getElementsByTagName("*");

	for(var i = 0;i < elements.length;i++){
		if(elements[i].className.indexOf(" ") >= 0){
			var classes = elements[i].className.split(" ");

			for(var j = 0;j < classes.length;j++){
				if(classes[j] == clsName){
					retVal.push(elements[i]);
				}
			}

		}else if(elements[i].className == clsName){
			retVal.push(elements[i]);
		}
	}
	return retVal;
}
/////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
/////////////////////////////////////////////////////////////////////////////////////////////////
function feedAnchor(anchorLink) {
	url = "item_"+anchorLink;
	setTimeout('scrollto(url)',200);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function anchorTo(which,amount_above,do_move) {
	if(document.getElementById(which)) {
		if(do_move) {
			$.scrollTo("#"+which, 0, {offset: {top:-amount_above-50}});
			$.scrollTo("#"+which, 300, {offset: {top:-amount_above}});
		} else {
			$.scrollTo("#"+which, 0, {offset: {top:-amount_above}});
		}
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////

function scrollto(obj) {
	var t=0;	
	var pad = 35;
	var strTop = document.getElementById(obj).style.top;
	if(strTop=="") doscroll(0,getScrollHeight(),0);
	else {
		pxPos = strTop.indexOf("px");
		targetYPos = parseInt(strTop.substring(0, pxPos)) - pad;
		var y = getScrollHeight(); //document[getDocElName()].scrollTop;
		clearTimeout(timer);
		
		//alert(getScrollHeight()+' / '+targetYPos+' / '+y);
		doscroll(targetYPos,y,t);
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function doscroll(targetYPos,y,t) {
	var speed = 6;
	var diff = targetYPos - y;
	var steps = diff/(speed*speed);
	t += (t+steps)/diff;
	newY = (t==1) ? y+diff : y + (diff * (-Math.pow(2, -20 * t/1) + 1));
	if(t) window.scrollTo(0, newY);
	
	if(t >= 1 || lastT == t || !t) clearTimeout(timer);
	else timer=setTimeout("doscroll("+targetYPos+","+y+","+t+")",1);
	
	lastT = t;
	
	return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function getDocElName(){
	if(document.compatMode && document.compatMode == "CSS1Compat") return "documentElement";
	else return "body";
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function handle(delta) {
	clearTimeout(timer);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function wheel(event){
	var delta = 0;
	if (!event) event = window.event;
	if (event.wheelDelta) {
		delta = event.wheelDelta/120; 
		if (window.opera) delta = -delta;
	} else if (event.detail) {
		delta = -event.detail/3;
	}
	if (delta)	handle(delta);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/* Initialization code. */
if (window.addEventListener)
	window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;


/////////////////////////////////////////////////////////////////////////////////////////////////
function di(id,name){
	if (document.images) document.images[id].src=eval(name+".src");
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function getadmin(url) {
	document.location.href=url+"/admin";
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function closeadmin(url) {
	parent.document.location="/"+url;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function cargoToolset(doshow) {
	if(doshow) {
		$("#toolset").css("display","block");
		//$("#toolsetframe").remove(); // breaks safari
		$(document).trigger("showToolset");
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function getnext(limit) {
	if(!intransition) {
		var this_spot = parseInt(document.getElementById('this_spot').value);
		this_spot++;
		if(this_spot >= (pid_list.length-1)) this_spot = 0;
		if(this_spot%limit == 0 && this_spot >= 0) changePage(Math.ceil((this_spot+1)/limit),limit);
		
		$.history.load(pid_list[this_spot]);
	}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function detectBrowser() {
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);
	return browser;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function getScrollHeight() {
    var y;
    if (self.pageYOffset) {
        y = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        y = document.documentElement.scrollTop;
    } else if (document.body) {
        y = document.body.scrollTop;
    }
    return parseInt(y);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function truncateText(trunc,len, dir) {
	if (trunc.length > len) {
		if(dir == "normal") trunc = trunc.substring(0, len)+'...';
		else if(dir == "center") trunc = trunc.substring(0, (len/2))+'…'+trunc.substring(trunc.length, trunc.length-(len/2));
		else trunc = '...'+trunc.substring(trunc.length, trunc.length-len);
	}
	return trunc;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function array_search(needle, haystack) {
    var key = '';
	for (key in haystack) {
		if (parseInt(haystack[key]) === parseInt(needle)) {
			return key;
		}
	}
	return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function arfind(ar,value) {
	for(i=0;i<ar.length;i++) {
		if(ar[i] == value) {
			spot = i;
			break;
		}
	}
	return spot;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Facebook comments
	function fbComments(variant, fbwidth, fbnum){
		addScript("http://connect.facebook.net/en_US/all.js#xfbml=1");
		var f_url =
			design =
			template =
			padding = "";
		var margin = "30px 0 30px 0";
		var element=".project_bottom";
		var colorscheme = (variant == "dark") ? "dark" : "light";
		
		fbwidth = (!fbwidth) ? 560 : fbwidth;
		fbnum = (!fbnum) ? 15 : fbnum;
		
		$(document).ready(function() {
			// Define the template and design
			design = $("input#design").val();
			template = $("input#template").val();
			// If it's feed go for it
			if($("#detailbottom").length > 0 || $("#content_container.permalink_page").length > 0 || $("#items_container.permapage").length > 0) {
            	// Set the current page URL
				f_url = encodeURIComponent(window.location.href.replace("#","/"));
				if(design == "ozfeed" || design == "ozfeed-alt") {
            		element = ".project_content .clear:last";
            	} else {
            		element = ".project_footer";
            	}
            	// Create the element
            	$(element).after('<div class="fb_comments" style="width: '+fbwidth+'; margin: '+margin+'; padding: '+padding+';"><fb:comments href="'+f_url+'" width="'+fbwidth+'" num_posts="'+fbnum+'" colorscheme="'+colorscheme+'"></fb:comments></div>');
			}
			// Also add a comment count on Feed
			if(template == "feed") {
				if($(".permalink").length > 0) {
					fbCommentCount();
					$(document).bind("paginationComplete", function(e, dataObj) {
						fbCommentCount();
					});
				}
			}
		});
		
		// For everything but Feed / SC
		$(document).bind("projectLoadComplete", function(e, pid){
			fbCommentLoad(pid, variant, fbwidth, fbnum);
        });
        
        // For everything but Feed / non-SC
		$(document).bind("SCprojectLoadComplete", function(e, pid){
			fbCommentLoad(pid, variant, fbwidth, fbnum);
        });
	}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Facebook comment count for Feed
	function fbCommentCount() {
		$(".project_footer:not(:has(>iframe))").each(function(){
			var permalink = $(".permalink a", this).attr("href");
			var domain = $("input#is_domain").val();
			if (domain == "false"){
				permalink = "http://cargocollective.com"+permalink;
			} else {
				permalink = "http://"+domain+permalink;
			}
			$(this).append('<br/><iframe src="http://www.facebook.com/plugins/comments.php?href=+'+permalink+'&permalink=1" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:130px; height:16px; margin-top: 10px;" allowTransparency="true"></iframe> ');
		});
	}
/////////////////////////////////////////////////////////////////////////////////////////////////
// Load FaceBook comments for non-feed designs
	function fbCommentLoad(pid, variant, fbwidth, fbnum) {
		var margin = "30px 0 30px 0";
		var timeout = 500;
		var template = $("input#template").val();
		var design = $("input#design").val();
		var domain = $("input#is_domain").val();
		var element=".project_bottom";
		var colorscheme = (variant == "dark") ? "dark" : "light";
		var position = "before";
		// If you're on a project
		if(array_search(pid, pr_list)){
		    // Load the Facebook comments script again, for whatever reason(s)
			$.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1");
		    f_url = encodeURIComponent(window.location.href.replace("/#","/").replace("#/","/").replace("#","/"));
			// FB events
			FB.Event.subscribe('xfbml.render', function(response){
				if(typeof reinitializeScrolling == 'function') {
					setTimeout("reinitializeScrolling(false,'main')",timeout);
				
				} else if(typeof shiftPosition == 'function') {
					setTimeout("shiftPosition()",timeout);
				}
				
		    });
			FB.Event.subscribe('comment.create', function(response){
				if(typeof reinitializeScrolling == 'function') {
					setTimeout("reinitializeScroll'ing(false,'main')",timeout);
				
				} else if(typeof shiftPosition == 'function') {
					setTimeout("shiftPosition()",timeout);
				}
		    });
		    FB.Event.subscribe('comment.remove', function(response){
				if(typeof reinitializeScrolling == 'function') {
					setTimeout("reinitializeScrolling(false,'main')",timeout);
				
				} else if(typeof shiftPosition == 'function') {
					setTimeout("shiftPosition()",timeout);
				}
		    });
			
			// Design specific interventions
			if(template == "limelight") {
				margin = "0 0 30px 0";
				
			} else if(design == "kant") {
				margin = "30px 30px 2px 30px";
				padding = "0 0 30px 0";
				
			} else if(design == "hegel") {
				margin = "30px auto 30px auto";
				
			} else if(design == "nietzsche") {
				margin = "-30px 0 50px 0";
			
			} else if(design == "kennedy" || design == "kennedy-alt") {
				element = ".project_footer";
				position = "after";
				
			}
			if(position = "after") {
				$(element).after('<div class="fb_comments" style="width: '+fbwidth+'; margin: '+margin+'; padding: '+padding+';"><fb:comments href="'+f_url+'" width="'+fbwidth+'" num_posts="'+fbnum+'" colorscheme="'+colorscheme+'"></fb:comments></div>');
			} else {
				$(element).before('<div class="fb_comments" style="width: '+fbwidth+'; margin: '+margin+'; padding: '+padding+';"><fb:comments href="'+f_url+'" width="'+fbwidth+'" num_posts="'+fbnum+'" colorscheme="'+colorscheme+'"></fb:comments></div>');
			}
		}
	}
/////////////////////////////////////////////////////////////////////////////////////////////////
function addScript(script_file) {
	var scrpt=document.createElement('script');
		scrpt.setAttribute('type','text/javascript');
		scrpt.setAttribute('src',script_file);   
	var hd=document.getElementsByTagName('head')[0];
		hd.appendChild(scrpt);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function addCSS(css_file) {
	var scrpt=document.createElement('link');
		scrpt.setAttribute('type','text/css');
		scrpt.setAttribute('rel','stylesheet');
		scrpt.setAttribute('href',css_file);   
	var hd=document.getElementsByTagName('head')[0];
		hd.appendChild(scrpt);
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function stripslashes( str ) {
    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function addslashes (str) {
	return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function in_array (needle, haystack, argStrict) {
    var key = '',
        strict = !! argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function testIE() {
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) return true;
	else return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////

