// JavaScript Document

jQuery(document).ready(function() {

	initFeaturedScroller();
	initHoverPortfolioItems();
	initScrollSecondary();
	initSelectFilters();
	initChangeSelects();

});

//Featured Scroller

function initFeaturedScroller() {

	var thisImgScroller = jQuery('#imgScroller');

	if (thisImgScroller.length > 0) {

		var speed = 7000;
		var itemContainer = thisImgScroller.find('ul.itemContainer');
		var imgScrollerItems = itemContainer.children('li');
		var imgScrollerSelectedItem = imgScrollerItems.filter('li.selected').length ? imgScrollerItems.filter('li.selected') : imgScrollerItems.filter(':first');
		var imgScrollerMask = thisImgScroller.find('div.imgScrollerMask');
		var imgScrollerNextPrevious = thisImgScroller.find('a.previous,a.next');
		var imgScrollerControls = thisImgScroller.find('ul.controls');
		var imgScrollerProgress = thisImgScroller.find('div.progress');
		var imgScrollerPause = imgScrollerProgress.next();
	
		var showControls = false;
		var showFullControls = false;
	
		if (thisImgScroller.hasClass('showControls')) {
	
			showControls = true;
	
		} else if (thisImgScroller.hasClass('showFullControls')) {
	
			showFullControls = true;
	
		}
	
		if (imgScrollerItems.length > 1) {

			var run;

			imgScrollerProgress.stop(true).width(0).animate({
		
				width : 970
		
			},speed);

			if (imgScrollerItems.length >= 3 && showFullControls) {

				imgScrollerItems.each(function(index){

					jQuery('<a href="">' + (index + 1) + '</a>').insertBefore(imgScrollerControls.children(':last')).click(function(){

						clearInterval(run);

						newsScroller(imgScrollerItems,imgScrollerMask,index,imgScrollerProgress,speed);

						run = setInterval( function() { newsScroller(imgScrollerItems,imgScrollerMask,"next",imgScrollerProgress,speed); }, speed);

						return false;

					});

				});

			}

			if (showControls || showFullControls) {

				imgScrollerControls.show();

			}

			itemContainer.width(thisImgScroller.width() * imgScrollerItems.length);

			run = setInterval( function() { newsScroller(imgScrollerItems,imgScrollerMask,"next",imgScrollerProgress,speed); }, speed);

			thisImgScroller.hover(

				function() {

					imgScrollerProgress.stop(true).width(0);

					imgScrollerPause.fadeIn(200);

					if (run != null) {

						clearInterval(run);

						run = null;

					}

				},

				function() {

					if (run == null) {

						run = setInterval( function() { newsScroller(imgScrollerItems,imgScrollerMask,"next",imgScrollerProgress,speed); }, speed);

					}

					imgScrollerProgress.stop(true).width(0).animate({

						width : 970

					},speed, "linear");

					imgScrollerPause.fadeOut(200);

				}

			);

		}

		imgScrollerNextPrevious.click(function(){

			clearInterval(run);

			if(jQuery(this).hasClass("previous")) {

				newsScroller(imgScrollerItems,imgScrollerMask,"prev",imgScrollerProgress,speed);

			} else {

				newsScroller(imgScrollerItems,imgScrollerMask,"next",imgScrollerProgress,speed);

			}
			
			imgScrollerPause.fadeOut(200);

			run = setInterval( function() { newsScroller(imgScrollerItems,imgScrollerMask,"next",imgScrollerProgress,speed); }, speed);

			return false;

		});

	}

}

function newsScroller(imgScrollerItems,imgScrollerMask,direction,imgScrollerProgress,speed) {

	var transitionSpeed = 500;

	imgScrollerProgress.stop(true).width(0).animate({

		width : 970

	},speed);

	var imgScrollerSelectedItem = imgScrollerItems.filter('.selected').length ? imgScrollerItems.filter('.selected') : imgScrollerItems.filter(':first');

	if (direction == "prev") {

		var next_image = (imgScrollerSelectedItem.prev().length) ? imgScrollerSelectedItem.prev() : imgScrollerItems.filter('li:last');

	} else if (direction == "next") {

		var next_image = (imgScrollerSelectedItem.next().length) ? imgScrollerSelectedItem.next() : imgScrollerItems.filter('li:first');

	} else {

		var next_image = imgScrollerItems.filter("li:eq(" + direction + ")");

	}

	imgScrollerItems.removeClass('selected');

	next_image.addClass('selected');

	imgScrollerMask.stop(true,true).scrollTo(next_image, 500);

}

function initHoverPortfolioItems() {

	var portfolioItems = jQuery("article.portfolioItem div.entry-content"); 

	portfolioItems.hover(function(){

		jQuery(this)

			.children("div.comments-link")
				.children("a")
					.stop(true)
					.animate({opacity : 1},300)
				.end()
			.end()
			.children("a.articleThumbnail")
				.children("img")
					.stop(true)
					.animate({opacity : 0.5},300);

	},function(){

		jQuery(this)

			.children("div.comments-link")

				.children("a")
					.stop(true)
					.animate({opacity : 0},300)

				.end()

			.end()

			.children("a.articleThumbnail")

				.children("img")
					.stop(true)
					.animate({opacity : 1},300);

	});

}

function initScrollSecondary() {
	
	var msie6 = jQuery.browser == 'msie' && jQuery.browser.version < 7,
		sidebar = jQuery("#secondaryInner"),
		primary = jQuery("#primary"),
		header = jQuery("#headerContainer"),
		main = jQuery("#mainContainer"),
		limit = header.height() + main.height(),
		tolerance = 30;

	if (!msie6 && sidebar.length > 0 && primary.height() > sidebar.height()) {

		var top = sidebar.offset().top;

		jQuery(window).scroll(function (event) {

			var y = jQuery(this).scrollTop();

			if (y >= top) {
				
				if (y + sidebar.height() >= limit - tolerance) {
				
					sidebar
						.removeClass('fixed')
						.addClass('fixedLimit')
						.css({
						
							"top" : main.height() - (sidebar.outerHeight() + tolerance)
							
						});
					
				} else {
				
					sidebar
						.removeClass('fixedLimit')
						.removeAttr('style')
						.addClass('fixed');
				}

			} else {

				sidebar
					.removeClass('fixedLimit')
					.removeAttr('style')
					.removeClass('fixed');
			}
		});
	}

};

function initSelectFilters() {
	
	var filterForm = jQuery("#filterForm");

	filterForm.find('select').change(function() {
		jQuery(this).closest("form").submit();
	});

}

function initChangeSelects() {

    var z = 9999,
		speed = 0,
		selects = jQuery('select.replace'),
		theDocument = jQuery(document);

    if (selects.length > 0) {

        function scrollList(direction, currentItem, ddOptions) {

            var currentItem = jQuery(currentItem);

            var scrollPosition = currentItem.position();

            if (scrollPosition == null) {
                scrollPosition = 0;
            } else {
                scrollPosition = scrollPosition.top;
            }

            if (direction == "up") {
                ddOptions.scrollTop(ddOptions.scrollTop() - currentItem.outerHeight());
            } else if (direction == "down") {
                ddOptions.scrollTop(ddOptions.scrollTop() + currentItem.outerHeight());
            } else {
                ddOptions.scrollTop(scrollPosition);
            }
        }

        function closeOptions(ddOptions, thisDd) {

            ddOptions.slideUp(speed);
            thisDd.removeClass("open");
            ddOptions.unbind("click");
            theDocument.unbind("click").unbind("keydown");

        }

        selects
			.wrap('<div class="select">')
			.parent()
			.prepend('<div class="trigger"><a href="#"><span></span></a></div><ul class="options"></ul>')
		.end()		
		.each(function () {

            var thisSelect = jQuery(this),
            	thisSelectOptions = thisSelect.children('option'),
            	thisSelectDisabled = false;

			// ---- If the select is disabled we need to build the list anyway but make a note to disable it
            if (thisSelect.attr("disabled")) {
                thisSelectDisabled = true;
            }

            // ---- Set the div we created before as a variable so we can refer to it later
            var thisDd = thisSelect.parent().css({'background' : 'none','zIndex' : z});

            // ---- Makes sure each subsequent dropdown has a lower z-index value so that when the menu drops down it doesn't overlap
			z--;
			
            // ---- Define the elements of the dd so we can easily refer to them later
            var ddTrigger = thisDd.children(":first-child"), //This is what opens the list
            	ddTriggerText = ddTrigger.find("a span"), //This is the text we will change when a selection is made
            	ddOptions = ddTrigger.next(), //This is the ul that contains the list items
            	ddOptionsOffset = ddOptions.offset();  //This is the offset values that we will use later to can detect whether the menu opens off the page

            // ---- Populate the lists with the options from the hidden select element
            var i = 0,
            	listHeight = 0;
			
            thisSelectOptions.each(function () {

                var thisOption = jQuery(this);

                if (jQuery(this).attr("selected")) {

                    ddTriggerText.text(thisOption.text());
                    ddOptions.append('<li class="current"><a href="#"><span>' + thisOption.text() + '</span><span class="hidden">' + i + '</span></a></li>');

                } else {

                    if (i == 0) {
                        ddTriggerText.text(thisOption.text());
                    }
                    ddOptions.append('<li><a href="#"><span>' + thisOption.text() + '</span><span class="hidden">' + i + '</span></a></li>');

                }

                var optionHeight = ddOptions.children(":last").outerHeight();
                listHeight = listHeight + optionHeight;
                i++;

            });

            // ---- Calculate the width and hide the list so it can be opened later
            var ddOptionsWidth = ddOptions.width();
            ddOptions.hide();

            // ---- Calculate the height
            if (listHeight > ddOptions.height()) {
                var scrollBarWidth = 17;
            } else {
                var scrollBarWidth = 0;
            }

			// ---- If the list is disabled
            if (thisSelectDisabled) {

                thisDd.addClass("disabled");

                ddTrigger.click(function (e) {

                    return false;

                });
			
			// ---- If the list is enabled
            } else {

                var listOptions = ddOptions.children("li");

                listOptions.children("a").click(function () {

                    var thisListItem = jQuery(this);

                    thisSelect
						.val(thisListItem.children('span.hidden').text())
						.children("option")
							.removeAttr("selected")
						.end()
						.children(":eq(" + thisListItem.parent().index() + ")")
							.attr("selected", true)
						.end()
						.trigger("change");
					
                    ddTriggerText.text(
						thisListItem
							.parent()
								.addClass("current")
							.end()
							.children(":first-child")
								.text()
					);
                    thisDd.removeClass("open");
                    ddOptions.slideUp(speed).find("li").removeClass("current");

                    return false;
                });

                // ---- check the position of the select list, if it goes off the page then change the default position
                ddOptions.css({
                    "top": (ddTrigger.innerHeight()) + "px",
                    "width": ddOptionsWidth + scrollBarWidth + "px",
                    "min-width": ddTrigger.innerWidth()
                });

                // ---- When the tooltip trigger is clicked the following code executes
                ddTrigger.click(function (e) {

                    e.stopPropagation();

                    // ---- if the selected class IS NOT present
                    if (!thisDd.hasClass("open")) {

                        selects.parent().removeClass("open").children(".options").hide();

                        thisDd.addClass("open");
                        ddOptions.stop(true, true).show(speed, function () {

                            scrollList("", ddOptions.children(".current"), ddOptions);

                            // ---- unbind document click and keydown to prevent event duplication
                            theDocument.unbind("click").unbind("keydown");

                            // ---- set up a click event on the document so if a user clicks outside of the options the options menu closes
                            theDocument.click(function () {
                                closeOptions(ddOptions, thisDd);
                            });

                            // ---- set up a click event on the options and use stop propagation to prevent the event above bubbling into it
                            ddOptions.click(function (e) {
                                e.stopPropagation();
                            });

                            // ---- Add a current class to the first option if one hasn't already been set
                            if (ddOptions.children("li.current").length == 0) {
                                ddOptions.children("li:first-child").addClass("current");
                            }

                            // ---- Add keyboard support: esc closes, up and down move through the options
                            theDocument.keydown(function (e) {

                                e.preventDefault(); //Prevents page from scrolling when the up arrow is pressed

                                if (e.keyCode == 27) { // Capture Esc key 27

                                    closeOptions(ddOptions, thisDd);

                                } else if (e.keyCode == 13) { // Capture Space key 13

                                    var thisListItem = ddOptions.children(".current");

                                    thisSelect.trigger("change");
                                    thisListItem.addClass("current");
                                    closeOptions(ddOptions, thisDd);

                                } else if (e.keyCode == 38) { // Capture Arrow Up key 38

                                    var currentItem = ddOptions.children("li.current:not(:first-child)").removeClass("current").prev();
                                    currentItem.addClass("current");
                                    thisSelect.children(":eq(" + currentItem.index() + ")").attr("selected", true);
                                    ddTriggerText.text(ddOptions.children("li.current").children().children(":first-child").text());
                                    scrollList("up", currentItem, ddOptions);

                                } else if (e.keyCode == 40) { // Capture Arrow Down key 40

                                    var currentItem = ddOptions.children("li.current:not(:last-child)").removeClass("current").next();
                                    currentItem.addClass("current");
                                    thisSelect.children(":eq(" + currentItem.index() + ")").attr("selected", true);
                                    ddTriggerText.text(ddOptions.children("li.current").children().children(":first-child").text());
                                    scrollList("down", currentItem, ddOptions);
                                }
                            });

                        });

                    }

                    return false;
                });

            }

        });

    }	
}
