﻿$(function () {
	
	$("a.new-window").live("click", function (evt) { window.open($(this).attr("href")); return false; });

	if ($(window).width() < 1180) $("#thecssawards").hide();
	
	$("#wrapper").css({
		
		paddingBottom: $("#footer").outerHeight(true)
		
	});

	$(".lightbox").fancybox({
		
		padding: 0,
		overlayColor: '#000',
		overlayOpacity: .8,
		titleShow: true,
		titlePosition: 'over',
		centerOnScroll: true
		
	});
	
    $(".content-rotator").each(function (idx) {

        var $container = $(this);
        $container.addClass("content-rotator-ready");

        var $nav = $("<ul class='content-rotator-nav'/>");

        var $content = $container.children(".content-rotator-item");

        $container.append($nav);
        var maxHeight = -1;

        for (var i = 0; i < $content.size(); i++) {

            var $contentItem = $content.eq(i);

            var $navItem = $("<li><a href='javascript:;' rel='" + i + "'>" + (i + 1) + "</a></li>");

            if ($contentItem.outerHeight(true) > maxHeight)
                maxHeight = $contentItem.outerHeight(true);

            $nav.append($navItem);

        }

        $nav.find("li a").click(function () {

            var $navItemLink = $(this);
            var $contentItem = $content.eq(parseInt($navItemLink.attr("rel")));

            $contentItem.addClass("active").fadeIn().siblings(".content-rotator-item.active").removeClass("active").fadeOut();
            $navItemLink.parent().addClass("active").siblings(".active").removeClass("active");

        });

        $container.height(maxHeight);

        var startIdx = Math.floor(Math.random() * $content.size());

        $content.filter(":not(:eq(" + startIdx + "))").hide();
        $content.eq(startIdx).addClass("active");
        $nav.find("li").eq(startIdx).addClass("active");

    });

    $(".sidebar .link-list .open-link").click(function () {

        var $link = $(this);
        var $container = $link.closest("li");
        var $contentItem = $container.children(".content");

        if (!$container.is(".active") && $contentItem.size() > 0) {

            $container.addClass("active").siblings(".active").removeClass("active").children(".content").slideUp();
            $contentItem.slideDown();

        }

    });

    $("#hide-content").click(function () {

        var $button = $(this);

        var $content = $("#content");
        var $inner = $content.children(".inner");

        if (!$content.is(".hidden") && !$content.is(":animated")) {

            $content.height($inner.outerHeight());
            $content.addClass("hidden");
            $inner.animate({

                top: -37,
                opacity: 0,
                easing: "easeOutQuad"

            }, 450);

            $button.text("Show").addClass("show").removeClass("hide");

        } else {

            $content.height("auto");
            $content.removeClass("hidden");

            $inner.animate({

                top: 0,
                opacity: 1,
                easing: "easeInQuad"

            }, 450, function () { $inner.css("opacity", null); $content.css("height", null); });

            $button.text("Hide").addClass("hide").removeClass("show");

        }

    });
    
    var slideInItem = function($item, callback) {
    	
    	if ($item.length > 0) {
    		
	    	$item.stop().show("slide", {
				
				direction: "left"
					
			}, 350, callback);
	    	
    	} else {
    		
    		if (typeof(callback) == "function")
    			callback();
    		
    	}
    	
    };
    
    var slideOutItem = function($item, callback) {
    	
    	if ($item.length > 0) {
    		
	    	$item.stop().hide("slide", {
				
				direction: "left"
					
			}, 200, callback);
	    	
    	} else {
    		
    		if (typeof(callback) == "function")
    			callback();
    		
    	}
    	
    };
    
    var refreshCufon = function(){
    	
    	Cufon.refresh("h2,h3,h4,h5,h6");
    	
    }
    
    if ($("#content").is(".col-slider")) {
    	
    	var cSlider = function($current, $end, endCallback) {
    		
    		if ($current[0] != $end[0]) {
    		
	    		slideOutItem($current.children(".children:visible"), function() {
	    			
	    			$current.find(".active a.selector").closest(".active").removeClass("active");
	    			
	    			var $next = $current.prev(".col");
	    			
	    			if ($next.length > 0 && $next[0] != $end[0]) {
	    				
	    				cSlider($next, $end, endCallback);
	    				
	    			} else {
	    				
	    				if (typeof(endCallback) == "function")
	    					endCallback();
	    				
	    			}
	    			
	    		});
    		
    		}
    		
    	};
    	
    	$("a.crosslink").click(function() {
    		
    		var $link = $(this);
    		var href = $link.attr("href");
    		
    		if (location.href.toString().indexOf($link.attr("href").split("#")[0]) >= 0) {
    			$("#content .col a.selector[rel=" + href.substring(href.indexOf("#") + 1) + "]").click();
    			return false;
    		}
    		
    	});
    	
    	var $columns = $("#content .col");
    	
    	var generateLocationHref = function() {
    		
    		var href = '';
    		
    		for(var i=0; i<$columns.length; i++) {
    			var $item = $columns.eq(i).find(".active a.selector");
    			if ($item.length == 1)
    				href += (href.length > 0 ? ':' : '') + $item.attr("rel");
    		}
    		
    		location.href = "#" + href;
    		
    	};
    	
    	var generateBackButton = function($item, $parentItem) {
    		
    		if ($item.children(".back").length == 0) {
				
				var $back = $('<ul class="back button-list"><li><a href="javascript:;">&lsaquo; Back</a></li></ul>');
				
				$back.click(function() {

					$parentItem.find(".active").removeClass("active");
					refreshCufon();
					
					slideOutItem($item, function() {
						
						slideInItem($parentItem, function() {

							refreshCufon();
							generateLocationHref();
							
						});
						
					});
					
				});
				
				$item.prepend($back);
				
			}
    		
    	};
    
    	$columns.find("a.selector").click(function() {
    		
    		var $link = $(this);
    		var $linkParent = $link.parent();
    		var $slideItem = $linkParent.closest(".children");
    		var rel = $link.attr("rel");
    		var $column = $linkParent.closest(".col");
    		var colIdx = $column.index();
    		
    		var $toShow = $columns.find(".children-" + rel);
    		var toShowColIdx = $toShow.closest(".col").index();
    		
    		var sameCol = colIdx == toShowColIdx;
    		
    		if (!$linkParent.is(".active")) {
    		
    			$linkParent.addClass("active").siblings(".active").removeClass("active");
    		
	    		if (!sameCol) {
	    			
	        		refreshCufon();
	    			
	    			cSlider($columns.eq($columns.length - 1), $column, function() {
			    		
			    		slideInItem($toShow, function() {
			    			
			    			var $nextLink = $toShow.find("a.selector:first");
			    			
			    			if ($nextLink.length == 1 && $columns.find(".children-" + $nextLink.attr("rel")).closest(".col").index() != toShowColIdx)
			    				$nextLink.click();
			    			
			    			generateLocationHref();
			    			
			    		});
			    		
			    	});
	
	    		} else {
	
	    			slideOutItem($linkParent.closest(".children"), function(){
	    				
	    				if ($toShow.children(".back").length == 0) {

	    					generateBackButton($toShow, $slideItem);
	    					
	    				}
	    				
	    				slideInItem($toShow, function() {
	
	    					generateLocationHref();
	    					
	    				});
	    				
	    			});
	    			
	    		}
	    		
    		}
    		
    		return false;
    		
    	});
    	
    	var startItem = location.href.split("#");
    	startItem = startItem[1];
    	
    	if (!startItem)
    		startItem = __TIME_OF_DAY;
    	
    	if (startItem) {
    		
	    	startItem = startItem.split(":");
	    	var $lastItem = null;
	    	var clickLastItem = true;
	    	
	    	for(var i=0; i<startItem.length; i++) {
	
	    		if (startItem[i].length > 0) {
	
	    			var $item = $("#content.col-slider .children-" + startItem[i]);
	    			
	    			$("#content.col-slider a.selector." + startItem[i]).parent().addClass("active");
		    		$item.show();
		    	
		    		if ($lastItem != null && $lastItem.closest(".col").index() == $item.closest(".col").index()) {
		    			$lastItem.hide();
		    			generateBackButton($item, $lastItem);
		    		}
		    			
		    		$lastItem = $("#content.col-slider .children-" + startItem[i]);
	    		
	    		}
	    		
	    	}
	    	
	    	refreshCufon();
	    	
	    	if ($lastItem && $lastItem.length > 0)
	    		$lastItem.find("a.selector:first").click();
	    	else {
	    		
	    		$("#content.col-slider .children-" + $("#content.col-slider .col:first a.selector:first").parent().addClass("active").end().attr("rel")).show();
	    		refreshCufon();
	    	}
    	
    	}
    	
    }
    
    $(".thumbnail-container>.item.video>a").prepend("<span class='play' title='Play Video' />");
    
    $(".media-selector a").live("click", function() {
    	
    	var $link = $(this);
    	//var $container = $link.closest(".media-selector").siblings(".media-container");
    	var $container = $(".media-container");
    	
    	$container.empty();
    	
    	if ($link.is(".video")) {
    		
    		$container.append("<div class='player'/>");
    		loadSwf($container.children(".player"), $link.attr("href"));
    		
    	} else if ($link.is(".image")) {
    		
    		var $image = $("<img />");
    		$image.attr("src", $link.attr("href"));
    		
    		$container.append("<div class='player'/>").children(".player").append($image);
    		
    	}
    	
    	if ($link.children(".title").length > 0)
    		$container.append("<div class='title'>" + $link.children(".title").text() + "</div>");
    	
    	if ($link.children(".caption").length > 0)
    	$container.append("<div class='caption'>" + $link.children(".caption").text() + "</div>");
    	
    	if ($(window).scrollTop() > $container.offset().top) {
    	
	    	$.scrollTo($container, {
	    		duration: 400
	    	});
    	
    	}
    	
    	return false;
    	
    });
    
    var loadSwf = function($elm, swfFile) {
    	
    	var ratio = 16/9;
    	
    	var width = $elm.width();
    	var height = Math.round(width/ratio) + 24;
    	
    	var so = new SWFObject('/wp-content/themes/kuletos/swf/player.swf','mpl', width, height,'9');
		so.addParam('allowfullscreen','true');
		so.addParam('allowscriptaccess','always');
		so.addParam('wmode','opaque');
		so.addVariable('file', swfFile);
		so.addVariable('screencolor', '#000000')
		so.write($elm[0]);
    	
    };
    
    var makeRelativeLink = function(href) {
    	
    	return href.replace(__BASE_URL, '');
    	
    };
    
    $("#content .ajax").live("click", function(){
    	
    	var $link = $(this);
    	var $destination = $("#content " + $link.attr("rel"));
    	
    	if (!$link.is(".active")) {
    	
    		$("#content .ajax.active").removeClass("active");
	    	$link.addClass("active");
	    	
	    	$destination.height($destination.height()).addClass("loading").empty();
	    	
	    	$destination.load($link.attr("href") + " #content " + $link.attr("rel") + ">*", function(data) {
	    		
	    		var $data = $(data);
	    		
	    		$destination.removeClass("loading");
	    		
	    		$destination.attr("class", $("#content " + $link.attr("rel"), $data).attr("class"));
	    		
	    		refreshCufon();
	    		$destination.height("auto");
	    		
	    		if ($(window).scrollTop() > $destination.offset().top) {
	    	    	
	    	    	$.scrollTo($destination, {
	    	    		duration: 400
	    	    	});
	        	
	        	}
	    		
	    	});
	    	
	    	location.href = '#!' + makeRelativeLink($link.attr("href"));
	    	//alert(pageTracker);
	    	//pageTracker._trackPageview(makeRelativeLink($link.attr("href")));
	    	
    	
    	}
    	
    	return false;
    	
    });
    
    var startLinkItem = location.href.split("#!")[1];
    
    if (startLinkItem) {
    	
    	$("#content .ajax[href=" + __BASE_URL + startLinkItem + "]").click();
    	
    } else {
    	
    	var $firstAjaxLink = $('#content .ajax:first');
    	var $destination = $('#content ' + $firstAjaxLink.attr('rel'));
    	
    	if ($destination.children().length == 0)
    		$firstAjaxLink.click();
    	
    }
    
    $("a.glossary-tooltip").live("mouseenter", function() {
    	
    	var $link = $(this);
    	
    	$link.attr("timeout", setTimeout(function() {
    		
    		$link.attr("timeout", "");
    	
	    	$link.removeClass("mouse-off");
	    	
	    	var $tooltip = $("body").children("#tooltip-" + $link.attr("rel"));
	    	
	    	var positionAndShowTooltip = function() {
	    		
	    		var top = $link.offset().top - $tooltip.outerHeight();
	    		var left = $link.offset().left;
	    		
	    		$tooltip.stop().css('visibility', 'hidden').show();
	    		
	    		if (left + $tooltip.outerWidth() > $(window).width()) {
	    			
	    			left -= $tooltip.outerWidth();
	    			$tooltip.addClass("reverse-x");
	    			
	    		} else {
	    			
	    			$tooltip.removeClass("reverse-x");
	    			
	    		}
	    		
	    		$tooltip.css({
	    			
	    			opacity: 0,
	    			visibility: 'visible',
	    			left: left,
	    			top: top - 8
	    			
	    		}).animate({
	    			
	    			opacity: 1,
	    			top: top
	    			
	    		}, 250);
	    		
	    	};
			
			if ($tooltip.length == 0) {
				
				$tooltip = $("<div class='tooltip' id='tooltip-" + $link.attr("rel") + "' />");
	    		$tooltip.append("<div class='inner'/>").append("<div class='tip'/>");
	    		$tooltip.hide();
	    		
	    		$("body").append($tooltip);
	    		
	    		$link.addClass("loading-tooltip");
	    	
		    	$.getJSON(__BASE_URL + '/wp-content/themes/kuletos/glossary.php?id=' + $link.attr('rel'), function(data, status) {
		    		
		    		$link.removeClass("loading-tooltip");
		    		
		    		$tooltip.children(".inner").html('<strong>' + data.post_title + ':</strong> ' + data.post_content);
		    		
		    		if (!$link.is(".mouse-off"))
		    			positionAndShowTooltip();
		    		
		    	});
	    	
			} else {
				
				if (!$link.is(".loading-tooltip"))
					positionAndShowTooltip();
				
			}
		
    	}, 350));
    	
    	return false;
    	
    }).live("mouseleave", function() {
    	
    	var $link = $(this);
    	
    	clearTimeout($link.attr("timeout"));
    	
    	var $tooltip = $("body").children("#tooltip-" + $link.attr("rel"));
    	
    	if ($tooltip.length > 0) {
    	
	    	$tooltip.animate({
				
				opacity: 0,
				top: "-=" + 8
				
			}, 250, function(){
				
				$tooltip.hide();
				
			});
    	
    	}
    	
    	$link.addClass("mouse-off");
    	
    	return false;
    	
    });

    var $quoteContainer = $("#sub-header .quotes");
    var quoteContainerMid = Math.round($quoteContainer.height() / 2);
    var $quote = $quoteContainer.children("blockquote");

    var quoteX = Math.floor(Math.random() * ($quoteContainer.width() - $quote.innerWidth()));
    var quoteY = Math.floor(Math.random() * ($quoteContainer.height() - $quote.innerHeight()));

    $quote.css({

        left: quoteX,
        top: quoteY,
        visibility: 'visible',
        opacity: 0

    });

    if (quoteY >= quoteContainerMid)
        $quote.addClass("reverse");
    
    $quote.delay(350).animate({
    	
    	opacity: 1
    	
    }, 2000, function() {
    	
    	$quote.css("opacity", null);
    	
    });
    
    $.getJSON("http://twitter.com/status/user_timeline/KuletosSF.json?count=1&callback=?", function(data, textStatus) {
    	
    	if (data.length > 0) {
    	
    		var date = new Date(data[0].created_at);
    		
    		var months = ['Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'];
    		
    		var isPM = date.getHours() > 12;
    		
    		var html = data[0].text;
    		
    		var reUrl = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    		var reMention = /[\@]+([A-Za-z0-9-_]+)/ig;
    		var reTopic = /[\#]+([A-Za-z0-9-_]+)/ig;
    		
    		html = html.replace(reUrl, '<a href="$1" class="new-window">$1</a>');
    		html = html.replace(reMention, '<a href="http://twitter.com/$1" class="new-window">@$1</a>');
    		html = html.replace(reTopic, '<a href="http://twitter.com/search?q=%23$1" class="new-window">#$1</a>');
    		
	    	$(".tweet p").html(html);
	    	
	    	$(".tweet cite").html(
	    			(date.getHours() - (isPM ? 12 : 0) ) + ':' +
	    			date.getMinutes() + ' ' + (isPM ? 'PM' : 'AM') + ' on ' +
	    			months[date.getMonth()] + ' ' +
	    			date.getDate() + ', ' +
	    			date.getFullYear() +
	    			' via ' + data[0].source);
    	
    	}
    	
    });

});
