
// BEGIN div slider integration
function widgetSlider(selector){
	jQuery(document).ready(function(){

		var msie6 = jQuery.browser == 'msie' && jQuery.browser.version < 7;

		if (!msie6) {
				var isSliding = false;
				var startPos = 0;
				var top = 0;
				jQuery(window).scroll(function (event) {
					if (!isSliding) {
						isSliding = true;
						// get pre-slide position
						top = jQuery(selector).offset().top - 16 - parseFloat(jQuery(selector).css('margin-top').replace(/auto/, 0));
					}
					// what the y position of the scroll is
					var y = jQuery(this).scrollTop();
					// whether that's below the form
					if (y >= top) {
						// if so, add the fixed class
						jQuery(selector).addClass('fixed');
					} else {
						// otherwise remove it
						jQuery(selector).removeClass('fixed');
						isSliding = false;
					}
				});
		}  
	});
};
// END div slider integration

// BEGIN sliding menu integration
function SDMenu(id) {
	if (!document.getElementById || !document.getElementsByTagName)
		return false;
	this.menu = document.getElementById(id);
	this.submenus = this.menu.getElementsByTagName("div");
	this.remember = true;
	this.speed = 3;
	this.markCurrent = true;
	this.oneSmOnly = false;
}

SDMenu.prototype.init = function() {
	var mainInstance = this;
	for (var i = 0; i < this.submenus.length; i++)
		this.submenus[i].getElementsByTagName("h2")[0].onclick = function() {
			mainInstance.toggleMenu(this.parentNode);
		};
	if (this.markCurrent) {
		var links = this.menu.getElementsByTagName("a");
		for (var i = 0; i < links.length; i++)
			if (links[i].href == document.location.href) {
				links[i].className = "current";
				break;
			}
	}
	if (this.remember) {
		var regex = new RegExp("sdmenu_" + encodeURIComponent(this.menu.id) + "=([01]+)");
		var match = regex.exec(document.cookie);
		if (match) {
			var states = match[1].split("");
			for (var i = 0; i < states.length; i++)
				this.submenus[i].className = (states[i] == 0 ? "collapsed" : "");
		}
	}
};

SDMenu.prototype.toggleMenu = function(submenu) {
	if (submenu.className == "collapsed")
		this.expandMenu(submenu);
	else
		this.collapseMenu(submenu);
};

SDMenu.prototype.expandMenu = function(submenu) {
	var fullHeight = submenu.getElementsByTagName("h2")[0].offsetHeight;
	var links = submenu.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++)
		fullHeight += links[i].offsetHeight;
	var moveBy = Math.round(this.speed * links.length);
	
	var mainInstance = this;
	var intId = setInterval(function() {
		var curHeight = submenu.offsetHeight;
		var newHeight = curHeight + moveBy;
		if (newHeight < fullHeight)
			submenu.style.height = newHeight + "px";
		else {
			clearInterval(intId);
			submenu.style.height = "";
			submenu.className = "";
			mainInstance.memorize();
		}
	}, 30);
	this.collapseOthers(submenu);
};

SDMenu.prototype.collapseMenu = function(submenu) {
	var minHeight = submenu.getElementsByTagName("h2")[0].offsetHeight + 16;
	var moveBy = Math.round(this.speed * submenu.getElementsByTagName("a").length);
	var mainInstance = this;
	var intId = setInterval(function() {
		var curHeight = submenu.offsetHeight;
		var newHeight = curHeight - moveBy;
		if (newHeight > minHeight)
			submenu.style.height = newHeight + "px";
		else {
			clearInterval(intId);
			submenu.style.height = "";
			submenu.className = "collapsed";
			mainInstance.memorize();
		}
	}, 30);
};

SDMenu.prototype.collapseOthers = function(submenu) {
	if (this.oneSmOnly) {
		for (var i = 0; i < this.submenus.length; i++)
			if (this.submenus[i] != submenu && this.submenus[i].className != "collapsed")
				this.collapseMenu(this.submenus[i]);
	}
};

SDMenu.prototype.expandAll = function() {
	var oldOneSmOnly = this.oneSmOnly;
	this.oneSmOnly = false;
	for (var i = 0; i < this.submenus.length; i++)
		if (this.submenus[i].className == "collapsed")
			this.expandMenu(this.submenus[i]);
	this.oneSmOnly = oldOneSmOnly;
};

SDMenu.prototype.collapseAll = function() {
	for (var i = 0; i < this.submenus.length; i++)
		if (this.submenus[i].className != "collapsed")
			this.collapseMenu(this.submenus[i]);
};

SDMenu.prototype.memorize = function() {
	if (this.remember) {
		var states = new Array();
		for (var i = 0; i < this.submenus.length; i++)
			states.push(this.submenus[i].className == "collapsed" ? 0 : 1);
		var d = new Date();
		d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
		document.cookie = "sdmenu_" + encodeURIComponent(this.menu.id) + "=" + states.join("") + "; expires=" + d.toGMTString() + "; path=/";
	}
};
// END sliding menu integration

// BEGIN simple thickbox inline
function showTB($someTitle, $someWidth, $someHeight, $someID, $isModal)	 {
	var newURL = "#TB_inline?height=$someHeight&width=$someWidth&inlineId=$someID&modal=$isModal";
	tb_show($someTitle, newURL);
}
// END simple thickbox inline

// BEGIN deferred twitter update
function fetchTwitter(){ //load the ads after everything else has already loaded
	if (PuffEffect.puffStopAll) {
		return;
	}

	// stop puff effect
	PuffEffect.puffStopAll = true;
	// set content immediately if cached
	var cachedContent = getCookie('twitter_content');
	if (cachedContent) {
		document.getElementById("twitter_update_list").innerHTML = cachedContent;
	}
	// otherwise grab the latest
	else {
		var twitter_content = document.createElement('script');
		twitter_content.src = 'http://twitter.com/statuses/user_timeline/bydesigngames.json?callback=twitterCachedCallback&count=8'; //Path to js file.
		twitter_content.type = 'text/javascript';

		document.getElementById('twitter_update_list').appendChild(twitter_content);
	}
	doPostFetchFX();
}

function twitterCallback2(twitters) {
	var statusHTML = [];
	for (var i=0; i<twitters.length; i++){
		var username = twitters[i].user.screen_name;
		var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
			return '<a href="'+url+'">'+url+'</a>';
		}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
			return	reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
		});
		statusHTML.push('<li><span>'+status+'</span><br /><a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
	}
	document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);

	if (delta < 60) {
		return 'less than a minute ago';
	} else if(delta < 120) {
		return 'about a minute ago';
	} else if(delta < (60*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (120*60)) {
		return 'about an hour ago';
	} else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
		return (parseInt(delta / 86400)).toString() + ' days ago';
	}
}

function setCookie(name, value, expires) {
	document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}

function getCookie(name) {
	if (document.cookie.length > 0) {
		var start = document.cookie.indexOf(name + "=");
		if (start != -1) { 
			start = start + name.length + 1; 
			var end = document.cookie.indexOf(";", start);
			if (end == -1) {
				end = document.cookie.length;
			}
			return unescape(document.cookie.substring(start, end));
		} 
	}
	return "";
}

function twitterCachedCallback(c) {
	// this will create the HTML. Function found inside blogger.js
	twitterCallback2(c);

	var content = document.getElementById("twitter_update_list").innerHTML;

	// expire cookie after 30 minutes
	var exp = new Date();
	exp.setTime(exp.getTime() + (1000 * 60 * 30));
	setCookie('twitter_content', content, exp);
}

function doPostFetchFX () {
	changeDisplayTag ('div_slider', 'block')
	changeDisplayTag ('twitter_bird_eye', 'block');
	var delay = randomXToY(3000, 4000);
	setTimeout("changeDisplayTag ('twitter_bird_eye', 'none')",delay);
	delay += randomXToY(50, 250);
	setTimeout("changeDisplayTag ('twitter_bird_eye', 'block')",delay);
	delay += randomXToY(500, 3000);
	setTimeout("changeDisplayTag ('twitter_bird_eye', 'none')",delay);
	delay += randomXToY(50, 250);
	setTimeout("changeDisplayTag ('twitter_bird_eye', 'block')",delay);
	delay += randomXToY(500, 2000);
	setTimeout("changeDisplayTag ('twitter_bird_eye', 'none')",delay);
	var extraBlink = randomXToY(0,1);
	if (extraBlink == 1) {
		delay += randomXToY(50, 250);
		setTimeout("changeDisplayTag ('twitter_bird_eye', 'block')",delay);
		delay += randomXToY(250, 500);
		setTimeout("changeDisplayTag ('twitter_bird_eye', 'none')",delay);
	}

	// restart puff effect
	setTimeout("PuffEffect.puffStopAll = false; PuffEffect.makeEffect('tweet_spawn', 24, 12);",delay + randomXToY(250, 500));
	
}

function changeDisplayTag (divName, visibility) {
	oldValue = document.getElementById(divName).style.display;

	document.getElementById(divName).style.display = visibility;
}

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

// BEGIN puff effect
// modified SmokeEffect from Gaya Design
// http://www.gayadesign.com/scripts/smokeeffect/
var PuffEffect = {

	imgLocation: "", //url to image here
	puffWidth: 80, //standard width
	puffHeight: 45, //standard height
	puffStopAll: false,

	//don't touch this:
	puffPos: new Array(),

	makeEffect: function(id, posX, posY) {
		//set position from the "parent"
		PuffEffect.puffPos[id] = new Array();
		PuffEffect.puffPos[id]['x'] = posX;
		PuffEffect.puffPos[id]['y'] = posY;

		//set a random time to start puffing
		if (PuffEffect.puffStopAll == false) {
			var time = (Math.floor(Math.random()*1001));
			setTimeout("PuffEffect.animate('" + id + "')", time);
		}
	},

	animate: function(id) {
			//create the puff cloud
			var puff = document.createElement("IMG");
			jQuery(puff).attr("src", PuffEffect.imgLocation);
			jQuery(puff).attr("alt", "tweet!");
			jQuery(puff).attr("class", "tweet");

			//create a temp id for the cloud so we can delete it later on
			var tempId = "tweet" + Math.floor(Math.random()*1001);
			jQuery(puff).attr("id", tempId);

			//append the cloud to the body
			jQuery(document.body).append(jQuery(puff));

			var objPos = jQuery('#' + id).offset();

			//do puff animation
			if (PuffEffect.puffStopAll == false) {
				jQuery(puff).css({
					top: (objPos['top'] + PuffEffect.puffPos[id]['y']) + "px",
					left: (objPos['left'] + PuffEffect.puffPos[id]['x']) + "px",
					zIndex: 25,
					opacity: 0.4
				});
				jQuery(puff).animate({
					width: PuffEffect.puffWidth + "px",
					height: PuffEffect.puffHeight + "px",
					marginLeft: "-" + (PuffEffect.puffWidth * randomXToY(0.5, 3)) + "px",
					marginTop: "-" + (PuffEffect.puffHeight * 1.5) + "px",
					opacity: 0.9
				},{
					duration: randomXToY(500, 1500)
				}).animate({
					marginTop: "-" + (PuffEffect.puffHeight * randomXToY(16, 28)) + "px",
					opacity: 0.0
				},{
					duration: randomXToY(1500, 3000)
				});
			}

			if (PuffEffect.puffStopAll == false) {

				//create timeout and run the animation again
				var time = 2500 + (Math.floor(Math.random()*2501));

				setTimeout("PuffEffect.animate('" + id + "')", time);

				//remove the old one
				setTimeout("jQuery(document).ready(function(jQuery){jQuery('#" + tempId + "').remove()});", 4200);
			}
	}
}
// END puff effect

// BEGIN list slider effect
function listItemSlider(selector){
	jQuery(document).ready(function($){
		var fadeDuration = 150; //time in milliseconds
		$(selector + ' li a').hover(function() {
			$(this).animate({ paddingLeft: '16px' }, fadeDuration);
			$(this).children('span').show().animate({ left: -5 }, fadeDuration);
		}, function() {
			$(this).animate({ paddingLeft: '4px' }, fadeDuration);
			$(this).children('span').animate({ left: -35 }, fadeDuration).fadeOut(fadeDuration);		  
		});
	});
}
// END list slider effect

// BEGIN div scroller 
function divScroller(selector, selectorb){
	jQuery(document).ready(function(){
		jQuery(selector).slider({
			animate: true,
			orientation: 'vertical',
			value: 100,
			change: handleSliderChange,
			slide: handleSliderSlide
		});
	});
}

function handleSliderChange(e, ui) {
	var maxScroll = jQuery("#div_scroll").attr("scrollHeight") - jQuery("#div_scroll").height();
	jQuery("#div_scroll").animate({scrollTop: ((100 - ui.value) * (maxScroll / 100))  }, 1000);
}

function handleSliderSlide(e, ui) {
	var maxScroll = jQuery("#div_scroll").attr("scrollHeight") - jQuery("#div_scroll").height();
	jQuery("#div_scroll").attr({scrollTop: ((100 - ui.value) * (maxScroll / 100)) });
}
// END div scroller

// BEGIN stray quotes integration
function newQuote(categories, linkphrase, id, strayurl, multi, offset, sequence, timer, disableaspect, loading, contributor){
	jQuery(document).ready(function($){			
		var divheight = $("div.stray_quote-" + id).height();
		$("div.stray_quote-" + id).height(divheight/2);
		$("div.stray_quote-" + id).css('text-align','center');
		$("div.stray_quote-" + id).css('padding-top',divheight/2);
		$("div.stray_quote-" + id).fadeOut('slow');
		$("div.stray_quote-" + id).html(loading).fadeIn('slow', function () {
																										 
			$.ajax({
				type: "POST",
				url: strayurl + "inc/stray_ajax.php",
				data: "action=newquote&categories=" + categories + "&sequence=" + sequence + "&linkphrase=" + linkphrase + "&widgetid=" + id + "&multi=" + multi + "&offset=" + offset + "&disableaspect=" + disableaspect + "&timer=" + timer + "&contributor=" + contributor,
				success: function(html){
					$("div.stray_quote-" + id).css('padding-top',null);
					$("div.stray_quote-" + id).css('height', null);
					$("div.stray_quote-" + id).after(html).remove();
				}
			});
		});
		
	})
}
// END stray quotes integration

// BEGIN toggle obj by ID
function showHide(obj) { 
	var someID = document.getElementById(obj);
	someID.style.display=(someID.style.display=="none")?"":"none";	
}
// END toggle obj by ID

// BEGIN jquery smooth scroll
function smoothScroll() {
	jQuery('a[href*="#"]').click(function() {
		if (location.pathname == this.pathname && location.host == this.host) {
			var target = jQuery(this.hash);
			target = target.size() && target || jQuery("[name=" + this.hash.slice(1) +']');
			if (target.size()) {
				target.ScrollTo(400);
				return false;
			}
		};
	});
}
// END jquery smooth scroll

// BEGIN greet box
var wpgb_cookie_exp = 365;

function wpgb_get_cookie(c_name) {
  if (document.cookie.length>0) {
	c_start=document.cookie.indexOf(c_name + "=");
	if (c_start!=-1) {
	  c_start=c_start + c_name.length+1;
	  c_end=document.cookie.indexOf(";",c_start);
	  if (c_end==-1) c_end=document.cookie.length;
	  return unescape(document.cookie.substring(c_start,c_end));
	}
  }
  return "";
}

function wpgb_set_cookie(c_name,value,expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+";path="+"/"+
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function wpgb_delete_cookie ( c_name )
{
  var now = new Date ();
  now.setTime ( now.getTime() - 1 );
  document.cookie = c_name += "=; expires=" + now.toGMTString();
}

function wpgb_get_delta(ref) {
  var visit_delta;
  var visit_last = wpgb_get_cookie("wpgb_visit_last-"+ref);

  if(visit_last==null || visit_last=="") {
	visit_delta = -1;
  }
  else {
	visit_last = new Date(visit_last);
	visit_delta = Math.round((new Date() - visit_last)/(1000 * 60));
  }
  return visit_delta;
}

function wpgb_get_closed(ref) {
  var closed = wpgb_get_cookie("wpgb_closed-"+ref);
  if(closed==null || closed=="") {
	return ""
  }
  else {
	return "true"
  }
}

function wpgb_get_logged_in() {
  var logged_in = wpgb_get_cookie("wpgb_logged_in");
  if(logged_in==null || logged_in=="") {
	return ""
  }
  else {
	return "true"
  }
}

// greet box onload
// display greet box when document is ready
function initGreetBox() {
	jQuery(document).ready(function($){
	  // set default referrer if none found
	  var ref = "default";
	  if(document.referrer){
	    ref = document.referrer;
	    m = ref.match(/^(http:\/\/[^\/]+)/i);
	    if(m){
	      ref = m[1].replace(".", "_");
	    }
	  }
	  // send request
	  $.ajax({
	    type: "GET",
	    url: "index.php",
	    data: "wpgb_public_action=query&visit_delta="+wpgb_get_delta(ref)+"&closed="+wpgb_get_closed(ref)+"&logged_in="+wpgb_get_logged_in()+"&referrer="+encodeURIComponent(document.referrer)+"&url="+encodeURIComponent(document.location)+"&title="+encodeURIComponent(document.title),
	    success: function(resp) {
	      if(resp != ''){
	        // show greeting message
	        $("#greet_block").hide().html(resp).fadeIn("def");
	        // bind close action
	        $("#greet_block_close").click(function(event){
	          event.preventDefault();
	          wpgb_set_cookie("wpgb_closed-"+ref,new Date(),wpgb_cookie_exp);
	          wpgb_set_cookie("wpgb_closed-"+ref,new Date(),wpgb_cookie_exp);
	          $("#greet_block").fadeOut("def");
	        });
	        // bind search action (if any)
	        $("#greet_search_link").click(function(){
	          action = $(this).attr("action");
	          if(action == "show"){
	            $("#greet_search_results").slideDown();
	            $(this).attr("action","hide");
	            $("#greet_search_link_text_show").hide();
	            $("#greet_search_link_text_hide").show();
	            $("#greet_search_text_show").hide();
	            $("#greet_search_text_hide").show();
	          }
	          else if(action == "hide"){
	            $("#greet_search_results").slideUp("fast");
	            $(this).attr("action","show");
	            $("#greet_search_link_text_show").show();
	            $("#greet_search_link_text_hide").hide();
	            $("#greet_search_text_show").show();
	            $("#greet_search_text_hide").hide();
	          }
	        });
	      }
	    }
	  });
	  // set cookie
	  wpgb_set_cookie("wpgb_visit_last-"+ref,new Date(),wpgb_cookie_exp);
	});
}
// END greet box

// BEGIN onload manager
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

addLoadEvent(initGreetBox);
addLoadEvent(function() {
	/* more code to run on page load */
});
// END onload manager
