$(document).ready(function() {
    caseStudyCycle();
    setupUseLabels();

    primaryNav();
    if ($("#checkboxList.jobs").length > 0) {
        moveJobList();
    }
    if ($(".formList").length > 0) {
        jobListEntry();
    }
    logoHover();

    blogArchive();

});

function blogArchive() {
    

	$('.archive .yearHeader').click(function() {
		var yearClicked = $(this).parent().get(0).id;
		if($('#'+yearClicked).hasClass('yearOpen')) {
			$('#'+yearClicked+' .yearList').slideUp('fast');
			$('#'+yearClicked).toggleClass('yearOpen');
		}
		else {
			$('#'+yearClicked+' .yearList').slideDown('fast');
			$('#'+yearClicked).toggleClass('yearOpen');
		}

		return false;
	});

	$('.archive .monthHeader').click(function() {
		var monthClicked = $(this).parent().get(0).id;
		if($('#'+monthClicked).hasClass('monthOpen')) {
			$('#'+monthClicked+' ul').slideUp('fast');
			$('#'+monthClicked).toggleClass('monthOpen');
		}
		else {
			$('#'+monthClicked+' ul').slideDown('fast');
			$('#'+monthClicked).toggleClass('monthOpen');
		}

		return false;
	});

	$('.archive .yearList .monthOpen ul').show();
	$('.archive .yearOpen .yearList').show();
}

function logoHover() {
    $("#logo a span.overlay").css("opacity", 0.5);
    $("#logo a span.h1Title").css("opacity", 0);
    logoMouseOver();
}

function logoMouseOver() {
    $("#logo a").bind("mouseenter",
        function() {
                $("#logo img").attr("src", "/images/heading_blur.png").css("opacity", 0.3);
                $("#logo span.overlay").stop().animate({ "height": "63px", "top": 0 }, 200);
                $("#logo a span.h1Title").stop().animate({ "opacity": "1" }, 200);
                //$("#logo a span.remove").stop().fadeIn("fast");
        }).bind("mouseleave", function() {
            $("#logo a img").attr("src", "/images/heading.png").css("opacity", 1);
            $("#logo a span.h1Title").stop().animate({ "opacity": "0" }, 200);
            //$("#logo a span.remove").stop().fadeOut("fast");
            $("#logo a span.overlay").stop().animate({ "height": "0", "top": "20px" });
        });
}
function jobListEntry() {
    $(".formList li").click(function() {
        var contentBox = '<span id="mover">' + $(this).text() + '</span>';
        $(this).after(contentBox);
        var inputPosition = $("#position input").position();
        $("#mover").animate({
            left: inputPosition.left,
            top: inputPosition.top
        }, 1000, "linear", function() {
            $("#mover").fadeOut();
            $("#position input").attr("value", $(this).text());
            $("#mover").remove();
        });


    }); 
}

function primaryNav() {
    if ($.browser.msie && (Number($.browser.version) < 7)) { 
        //Do nothing 
    } 
    else {
        $('#primaryNav li').prepend('<div class="first"></div><div class="second"></div>');
        primaryNavMouseOver();
        primaryNavMouseOut();
    }
}

function primaryNavMouseOver() {
    $('#primaryNav li a').mouseover(function() {
        var queueNumber = $(this).parent().children("div").queue("fx");
        if (!$(this).parent().hasClass("current") && queueNumber < 2) {
            $(this).parent().children("div").animate({
                width: "52%"
            }, 200);
        }
        $(this).parent().children("div").dequeue();
    });
}

function primaryNavMouseOut() {
    $('#primaryNav li a').mouseout(function() {
        if (!$(this).parent().hasClass("current")) {
            var queueNumber = $(this).parent().children("div").queue("fx");
            $(this).parent().children("div").animate({
                width: "0"
            }, 200);
            $(this).parent().children("div").dequeue();
        }
    });
}








function caseStudyCycle() {

    $("#caseStudyList>li").hide();
    if ($("#caseStudyPager").length==0 ){
        var ul = '<ul id="caseStudyPager" class="fc tac col_37fr">';
        for (i = 0; i < $("#caseStudyList>li").length; i++) {
            ul = ul + '<li><span>'+(i+1)+'</span></li>';
        }
        ul = ul + '</ul>';
        $("#caseStudyPreview").prepend(ul);
        $("#caseStudyList>li").eq(0).show();
        $("#caseStudyPager li").eq(0).addClass("current");
        $("#caseStudyPager li").click(function() { $(document).stopTime("caseStudyPager"); goToCaseStudyPreview($("#caseStudyPager li").index(this), $("#caseStudyList>li").length); });
    }

    var times = $("#caseStudyList>li").length;
    $(document).everyTime(6000, "caseStudyPager", function(i) {
        goToCaseStudyPreview(i, times);
    }, times);
}

function goToCaseStudyPreview(num, max) {
    $("#caseStudyList>li[style!=display: none;]").fadeOut("fast");
    $("#caseStudyPager li.current").removeClass("current");
    if (num == max) { num = 0; }
    $("#caseStudyList>li").eq(num).fadeIn("fast");
    $("#caseStudyPager li").eq(num).addClass("current");   
}



/* A function which sets the element value of a form to the label text based on the element having the
useLabel class */
function setupUseLabels() {
    var useLabelElements = $(".useLabel");

    useLabelElements.each(function(i) {
        var element = $(useLabelElements[i]);

        setElementValueWithLabel(element, true);
        
        element.focus(function() {
            var labelValue = $("label[for='" + $(this).attr("id") + "']").addClass("hide").text();
            if ($(this).val() == labelValue)
                $(this).val(""); });
        
        element.blur(function() { setElementValueWithLabel($(this),false); });
    });
}

/* Actually sets the element value to the label text */
function setElementValueWithLabel(element, override) {
    var labelValue = $("label[for='" + element.attr("id") + "']").addClass("hide").text();
    if(override || element.val().length == 0)
        element.val(labelValue);
}

function moveJobList() {

    var clonedList = $("#checkboxList.jobs").clone();
    var clonedListInputs = $("li div input", clonedList);

    $(".contentForm #checkboxList.jobs").addClass("hide");

    clonedListInputs.click(function() {
        var id = $(this).attr("id");
        $(".contentForm #checkboxList #" + id).attr("checked", "checked");
    });

    clonedList.insertBefore("#tabbedRight #innerContent form");

}





/* Jquery Timer*/

/**
* jQuery.timers - Timer abstractions for jQuery
* Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* Date: 2009/02/08
*
* @author Blair Mitchelmore
* @version 1.1.2
*
**/

jQuery.fn.extend({
    everyTime: function(interval, label, fn, times, belay) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times, belay);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.event.special

jQuery.extend({
    timer: {
        global: [],
        guid: 1,
        dataKey: "jQuery.timer",
        regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseFloat(result[1]);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times, belay) {
            var counter = 0;

            if (jQuery.isFunction(label)) {
                if (!times)
                    times = fn;
                fn = label;
                label = interval;
            }

            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
                return;

            if (times && times.constructor != Number) {
                belay = !!times;
                times = 0;
            }

            times = times || 0;
            belay = belay || false;

            var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

            if (!timers[label])
                timers[label] = {};

            fn.timerID = fn.timerID || this.guid++;

            var handler = function() {
                if (belay && this.inProgress)
                    return;
                this.inProgress = true;
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
                this.inProgress = false;
            };

            handler.timerID = fn.timerID;

            if (!timers[label][fn.timerID])
                timers[label][fn.timerID] = window.setInterval(handler, interval);

            this.global.push(element);

        },
        remove: function(element, label, fn) {
            var timers = jQuery.data(element, this.dataKey), ret;

            if (timers) {

                if (!label) {
                    for (label in timers)
                        this.remove(element, label, fn);
                } else if (timers[label]) {
                    if (fn) {
                        if (fn.timerID) {
                            window.clearInterval(timers[label][fn.timerID]);
                            delete timers[label][fn.timerID];
                        }
                    } else {
                        for (var fn in timers[label]) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }

                    for (ret in timers[label]) break;
                    if (!ret) {
                        ret = null;
                        delete timers[label];
                    }
                }

                for (ret in timers) break;
                if (!ret)
                    jQuery.removeData(element, this.dataKey);
            }
        }
    }
});

jQuery(window).bind("unload", function() {
    jQuery.each(jQuery.timer.global, function(index, item) {
        jQuery.timer.remove(item);
    });
});