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

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

$(function(){
	
	$("ul.choose a").click(function(){
		
		var ul = $(this).closest("ul.choose");
		
		if ($(this).parent().next("li").length) {
			
			ul.removeClass("choose-secondary");
			
		} else {
			
			ul.addClass("choose-secondary");
			
		}
		
		ul.find("li").removeClass("choose-selected");
		$(this).parent().addClass("choose-selected");
		
	}).eq(0).click();
	
	$("#desc a").click(function(){
		
		$("div.desc").stop().slideUp();
		$("#" + $(this).closest("li").attr("id") + "-div").stop().slideDown();
		
		return false;
		
	});
	
	
	$("#destiny a").click(function(){
		
		var li = $(this).closest("li");
		var ul = $("#destiny");
		
		if (li.attr("id") == "choose-self") {
			
			$("#animals a").stop().animate({opacity: 1}, {duration: 200});
			
		} else {
			
			$("#animals a").stop().animate({opacity: 0.13}, {duration: 200});
			setTimeout(function(){
				
				function getRandomInt(min, max) {
					return Math.floor(Math.random() * (max - min + 1)) + min;
				}
				
				function getDuration(n, r){
					
					return 200 - (150 * ((r - n) / r));
					
				}
				
				var p = getCookie("previous");
				var n = 0;
				var r = getRandomInt(12, 15);
				
				while (r == p) { r = getRandomInt(12, 15); }
				
				setCookie("previous", r);
				
				var o = $("#animal-giraffe");
				
				function show(){
					
					o.animate({opacity: 1}, {duration: getDuration(n, r), complete: function(){
						
						if (n < r) {
							
							$(this).animate({opacity: 0.13}, {duration: getDuration(n, r), complete: function(){
								
								if (o.next("a").length) {
									
									o = o.next("a");
									
								} else {
									
									o = o.closest("div").find("a").eq(0);
									
								}
								
								n++;
								show();
								
							}});
							
						} else {
							
							function blink(callback) {
								
								o.delay(50).animate({opacity: 0.13}, 30).delay(50).animate({opacity: 1}, 30, callback);
								
							}
							
							blink();
							blink();
							blink(function(){
								
								window.location.assign(o.attr("href"));
								
							});
							
						}
						
					}});
					
				}
				
				show();
				
			}, 250);
			
		}
		
		return false;
		
	});
	
});
