$(function () {

    var debug = function (html) {

        alert(html);

    };

    var debugEvent = function (evt) {

        var output = evt.type + "\n\n";

        debug(output);

        debugObject(evt);

    };

    var debugObject = function (obj) {

        var output = "";

        for (var p in obj)
            output += p + ":\n" + obj[p] + "\n\n";

        debug(output);

    };

    $("a.new-window").live("click", function () { window.open($(this).attr("href")); return false; });

    $("#menu-main-navigation>li").last().addClass("end");
    
    $(".push").height($(".footer").outerHeight(true));
    
    $(".nav-container .menu .menu-item").mouseenter(function () {

        $(this).addClass("menu-item-hover");
        Cufon.refresh();

    }).mouseleave(function () {

        $(this).removeClass("menu-item-hover");
        Cufon.refresh();

    });

    $("input[type=text].masked").each(function (idx) {

        $(this).val($(this).attr("title"));

        $(this).bind("focus", function () {

            if ($(this).val() == $(this).attr("title")) {
                $(this).val("");
                $(this).addClass("active");
            }

        });

        $(this).bind("blur", function () {

            if ($(this).val() == "") {
                $(this).val($(this).attr("title"));
                $(this).removeClass("active");
            }

        });

    });

    $("#subscribe-form").submit(function () {

        var $form = $(this);

        $.post($form.attr("action"), $form.serialize(), function (data) {

            alert(data);

        });

        return false;

    });

    var isOverlapped = function (bounds1, bounds2) {

        /*if (bounds1.left >= bounds2.left - 50 && bounds1.left <= bounds2.right - 50 ||
        bounds2.left >= bounds1.left - 50 && bounds2.left <= bounds1.right - 50) {

        return true;

        } else {*/

        var bounds2temp = bounds2;

        bounds2.top = bounds2temp.bottom;
        bounds2.bottom = bounds2temp.top;

        var denom = ((bounds2.bottom - bounds2.top) * (bounds1.right - bounds1.left)) - ((bounds2.right - bounds2.left) * (bounds1.bottom - bounds1.top));

        if (denom != 0) {

            //float ua = (point4.X - point3.X) * (point1.Y - point3.Y) - (point4.Y - point3.Y) * (point1.X - point3.X);
            //float ub = (point2.X - point1.X) * (point1.Y - point3.Y) - (point2.Y - point1.Y) * (point1.X - point3.X);
            var ua = (bounds2.right - bounds2.left) * (bounds1.top - bounds2.top) - (bounds2.bottom - bounds2.top) * (bounds1.left - bounds2.left);
            ua /= denom;

            var ub = (bounds1.right - bounds1.left) * (bounds1.top - bounds2.top) - (bounds1.bottom - bounds1.top) * (bounds1.left - bounds2.left);
            ub /= denom;

            if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {

                return true;

            }

        }

        //}

        return false;

    };

    /*isOverlapped({

    left: 0,
    top: 0,
    right: 10,
    bottom: 10

    }, {

    left: 3,
    top: 7,
    right: 10,
    bottom: 0

    });*/

    var genLine = 0;

    var generateBubblePosition = function (bounds, positions, $bubble) {

        var pos = {};

        if (positions.length == 0) {

            pos.left = Math.round((bounds.width - $bubble.width()) / 2) + ($bubble.next().length > 0 ? Math.round(Math.random() * 140) : 0);
            pos.top = Math.round(Math.random() * 50);

        } else {

            lastPos = positions[positions.length - 1];

            var newBounds = {

                left: lastPos.right,
                top: lastPos.top

            };

            if (positions.length == 1 && $bubble.width() < lastPos.left) {

                newBounds.left = 0;

            } else if (positions.length > 1 && genLine == 0 &&

                ((newBounds.left >= positions[0].left && newBounds.left <= positions[0].right) || (newBounds.left + $bubble.width() <= positions[0].right && newBounds.left + $bubble.width() >= positions[0].left))

            ) {

                newBounds.left = positions[0].right;
            }

            if (newBounds.left + $bubble.width() > bounds.width) {

                newBounds.left = 0;
                newBounds.top = lastPos.bottom;

                for (var i = 0; i < positions.length; i++)
                    if (positions[i].bottom > newBounds.top)
                        newBounds.top = positions[i].bottom;

                genLine++;

                if ($bubble.next().length == 0)
                    newBounds.left = Math.round((bounds.width - $bubble.width()) / 2);

            }

            pos.left = newBounds.left - Math.round(Math.random() * 40) + Math.round(Math.random() * 40);
            pos.top = newBounds.top - Math.round(Math.random() * (newBounds.top < 60 ? newBounds.top : 60));

        }

        pos.right = pos.left + $bubble.width();
        pos.bottom = pos.top + $bubble.height();

        return pos;

    };

    $(".bubble-container").each(function () {

        var $container = $(this);

        var $bubbles = $(".bubble", $container);

        $bubbles.fadeTo(0, 0);

        $bubbles.sort(function () { return (Math.round(Math.random()) - 0.5); });
        $bubbles.remove();

        for (var i = 0; i < $bubbles.length; i++)
            $container.append($bubbles[i]);

        $bubbles = $(".bubble", $container);

        var positions = [];
        var rows = [];

        rows[0] = {

            bounds: { left: 0, top: 0, width: 0, height: 0 },
            bubbles: []

        };

        for (var i = 0, row = 0; i < $bubbles.length; i++) {

            var $bubble = $bubbles.eq(i);

            if (rows[row].bounds.width + $bubble.width() > $container.width()) {

                rows[row].bounds.left = Math.round(($container.width() - rows[row].bounds.width) / 2);

                var top = rows[row].bounds.top + rows[row].bounds.height;

                row++;

                rows[row] = {

                    bounds: { left: 0, top: top, width: 0, height: 0 },
                    bubbles: []

                };

            }

            rows[row].bubbles.push($bubble);

            if ($bubble.height() > rows[row].bounds.height)
                rows[row].bounds.height = $bubble.height();

            rows[row].bounds.width += $bubble.width();

        }

        rows[rows.length - 1].bounds.left = Math.round(($container.width() - rows[rows.length - 1].bounds.width) / 2);

        var maxOffsetBottom = 0;
        var fadedBubbles = 0;

        for (var i = 0; i < rows.length; i++) {

            var row = rows[i];
            var lastRight = 0;

            //debugObject(row.bounds);

            for (var c = 0; c < row.bubbles.length; c++) {

                var $bubble = row.bubbles[c];

                var pos = {

                    top: row.bounds.top,
                    left: row.bounds.left + lastRight

                };

                if ($bubble.height() < row.bounds.height)
                    pos.top = Math.round(Math.random() * Math.round((row.bounds.height - $bubble.height()) / 2)) + row.bounds.top;

                pos.top += -(row.bounds.top > 0 ? Math.round(Math.random() * 100) : -Math.round(Math.random() * 60));
                pos.left += -(row.bounds.left > 0 ? Math.round(Math.random() * 30) : -Math.round(Math.random() * 20));

                $bubble.css(pos).delay(Math.random() * 400).fadeTo(250, 1, function () { $(this).css("opacity", ""); });

                fadedBubbles++;

                lastRight += $bubble.width();

                if ($bubble.position().top + $bubble.height() > maxOffsetBottom)
                    maxOffsetBottom = $bubble.position().top + $bubble.height();

            }

        }

        $container.height(maxOffsetBottom);

        $bubbles.mouseenter(function () {

            var $bubble = $(this);
            $bubble.addClass("bubble-hover").siblings(".bubble").removeClass("bubble-hover").stop().fadeTo(250, .3);

        }).mouseleave(function () {

            var $bubble = $(this);
            $bubble.siblings(".bubble").stop().fadeTo(250, 1, function () {

                $(this).css("opacity", "");

            });

        });

    });

    $(".lightbox").click(function () {

        var $link = $(this);

        var options = {

            'padding': 0,
            'autoScale': false

        };

        if ($link.is(".lightbox-yt")) {

            options.href = $link.attr("href").replace(new RegExp("watch\\?v=", "i"), 'v/');
            options.width = 680;
            options.height = 495;
            options.type = 'swf';
            options.swf = {
                'wmode': 'transparent',
                'allowfullscreen': 'true'
            };

        }

        $.fancybox(options);

        return false;

    });
    
    $(".bubble-twitter").each(function() {
    	
    	var $bubble = $(this);
    	var count = $bubble.data("twitter-offset") ? parseInt($bubble.data("twitter-offset")) + 1 : 1;
    	
    	$.getJSON("/handlers/proxy.ashx?_url=" + encodeURIComponent("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" + $bubble.data("twitter-account") + "&trim_user=t&include_rts=t&count=" + count), null, function (data) {

    		var tweet = data[count-1];
    		
    		$(".excerpt", $bubble).text(tweet.text.length < 60 ? tweet.text : tweet.text.substring(0,60) + "...");
    		
    		$bubble.children("a").attr("href", "http://twitter.com/" + $bubble.data("twitter-account") + "/status/" + tweet.id_str).addClass("new-window");
    		
    	});
    	
    });
    
    $(".image-viewer").each(function() {
    	
    	var $viewer = $(this);
    	var $large = $(".large-image", $viewer);
    	var $thumbnails = $(".thumbnails a", $viewer);
    	
    	$thumbnails.click(function() {
    	
    		var $link = $(this);

    		if (!$link.is(".active")) {
    		
    			$link.addClass("active").siblings(".active").removeClass("active");
    			$large.empty().append("<img src='" + $link.attr("href") + "' /><cite>" + $link.attr("title") + "</cite>");
    		
    		}
    		
    		return false;
    		
    	}).first().click();
    	
    });
    
    $(".drop-down-link-list").each(function() {
    	
    	var $container = $("<div class='drop-down-link-list-container' />");
    	var $list = $(this);
    	var $items = $("li", $list);
    	var $selected = $items.filter("li.selected");
    	var $visibleSelected = $("div.selected", $container);
    	
    	$list.before($container);
    	$container.append($list);
    	
    	$list.hide();
    	
    	var setSelected = function($newSelected) {
    		
    		var $oldSelected = $items.eq(parseInt($visibleSelected.data("index")));
    		
    		if ($oldSelected.length)
				$oldSelected.show();
    		
    		if (!$visibleSelected.length) {
    			
    			$visibleSelected = $("<div class='selected' />");
    			$container.prepend($visibleSelected);
    			
    		}
    		
    		$newSelected.hide();
    		
    		$visibleSelected.empty().data("index", $newSelected.index()).append($newSelected.html());

    	};
    	
    	setSelected($selected.length ? $selected : $items.first());
    	
    	$visibleSelected.click(function() {
    		
    		if (!$container.is(".open")) {
    		
    			$container.addClass("open");
    			$list.show();
	    		
	    		return false;
    		
    		} else {
    			
    			$list.hide();
    			$container.removeClass("open");
    			
    			return false;
    			
    		}
    		
    	});
    	
    	$items.click(function() {
    		
    		setSelected($(this));
    		
    		$list.hide();
    		$container.removeClass("open");
    		
    	});
    	
    });

});
