// ============================
// The feature carousel object
// ============================

// Declare the objects we want to operate on
var features = {
	itself: $("#features")
};
features.controls = $(features.itself).find("#featureControls");
features.items = $(features.itself).find(".featureItem");
features.thumbList = $(features.itself).find("#featureThumbList");
features.thumbWrap = $(features.itself).find("#featureThumbWrap");
features.thumbs = $(features.thumbList).find("li");
features.thumbFirst = $(features.thumbs).eq(1);

// Get their necessary values
features.itselfWidth = $(features.itself).width();
features.itemsLength = $(features.items).length;
features.thumbsLength = $(features.thumbs).length;
features.thumbWrapWidth = $(features.thumbWrap).width();
features.thumbPadding = parseFloat($(features.thumbFirst).css("paddingLeft"))*2;

// Get the more complex values
features.thumbWidth = $(features.thumbFirst).width()+features.thumbPadding;
features.thumbListWidth = (features.thumbsLength)*(features.thumbWidth);

// Set up "slides" for the thumbshift
features.slideCur = 1;
features.slideLength = Math.ceil(features.thumbListWidth/features.thumbWrapWidth); // Total number of "slides"
features.slideThumbsLength = Math.floor(features.thumbWrapWidth/features.thumbWidth); // Thumbs per slide
features.slideWidth = features.slideThumbsLength*(features.thumbWidth+3);

function killLoop(){
	clearInterval(featureTime);
}

$(document).ready(function(){


	//============================================
	// Global functions
	//============================================

	$.fn.getClassIndex = function(){
		if($(this).attr('class')){
			return ($(this).attr('class').match(/views-row-([0-9]+)/)[1]-1);
		}
	}
	$.fn.getIndex = function(){
		  var parentSet=$(this).parent().children();
	    return $(parentSet).index(this);
	};
	
	$.fn.toggleCur = function(){
		  if($(this).hasClass("cur")){
			  return $(this).removeClass("cur");
		  } else {
			  return $(this).addClass("cur");
		  }
	};
	$.fn.loopNext = function(){
		 if($(this).is(":last-child")){
		   return $(this).siblings(":first");
		 } else {
       return $(this).next();
		 }
	};
	$.fn.loopPrev = function(){
		 if($(this).is(":first-child")){
		   return $(this).siblings(":last");
		 } else {
       return $(this).prev ();
		 }
	};
	

	//============================================
	// Alert collapse - save state as a cookie
	//============================================
	$("div.alert").each(function(){
		  var alertId = $(this).attr("id");
		  var cookieState = $.cookie(alertId);
		  if (cookieState == "hidden"){
			  $(this).addClass("hide");
	  	}
	});
	$(".closeAlert").click(function(){
		var parentAlert = $(this).parents(".alert");
		var alertId = $(parentAlert).attr("id");
	  $(parentAlert).fadeOut();
	  $.cookie(''+ alertId +'', 'hidden', { expires: 9999 });
	});
	
	//============================================
	// Big Feature Carousel
	//============================================	
	$("#features .featureItem img").each(function(){
		imageSrc = $(this).attr("src");
		$(this).attr("src","");
		$(this).load(function(){
		    $(this).parents(".featureItem").addClass("featureLoaded");
		});
		$(this).attr("src",imageSrc);
	});
	
	$("img").each(function(){
		imageSrc = $(this).attr('src');
		$(this).attr('src','');
		$(this).load(function(){
		    $(this).data('loaded','true');
		});
		$(this).attr('src',imageSrc);
	});
	

	

  // Alerts for poorly-formed Feature Carousels - ones with more images than thumbs, or vice versa

	if (features.itself.length>1){

		alert("Sorry, but you can only have one 'features' div per page.");

	}

	if (features.itemsLength!=features.thumbsLength){

		alert("You have a different number of features than you do thumbs! The feature carousel will not work properly.");

	}

	

  // Place the nav controls if there are more items than are visible in the thumbList

  if (features.thumbWrapWidth<features.thumbListWidth){

	  $(features.controls).append('<a href="#" id="featurePrev" class="featureNav">Show previous thumbnails</a><a href="#" id="featureNext" class="featureNav">Show next thumbnails</a>');

  }

	

  // On click, check to see if the carousel is animating. If not, move the carousel to the selected slide.

	$("#featureControls li a").click(function(){

		if (!(features.controls).hasClass("animating")){

			if ($(this).parent().is(":not(.cur)")) {

				var thumbNumber = $(this).parent().getClassIndex();

	      clearInterval(featureTime);

				featureMove(thumbNumber);

			}

		}

		return false;

	});



  // Make all featureItems visible (all but the first should have the .hide class). This allows them to load.

  $("#features .featureItem").css("display","block");

  $("#features .featureItem:not(.cur)").css("zIndex","-100");

  $("#features .featureItem:not(.cur) .featureDescription").hide();



  // On click events for the feature thumb navs. Stops the auto-advancing of the thumbs (but not the carousel).

  $("#features #featureNext").click(function(){

//    thumbShift("next",features);

    clearInterval(featureTime);

	featureMove();

    features.userControl = true;

    return false;

  });

  $("#features #featurePrev").click(function(){

//    thumbShift("prev",features);

    clearInterval(featureTime);

	featureMove(-1);

    features.userControl = true;

    return false;

  });

	

	

});





//============================================

// Scrolling through thumbnails

//============================================

function thumbShift(direction,features){

		

	var movement;

		

	// Set the thumbShift action for three cases, "prev", "next", or other.

	switch (direction) {

		

		case "prev":

     if (features.slideCur !== 1){

	     movement = "+=" + features.slideWidth;

       features.slideCur -= 1;

     } else {

	     movement = "-"+((features.slideLength-1)*features.slideWidth);

       features.slideCur = features.slideLength;

     }

		break;

		

		case "next":

    if (features.slideCur !== features.slideLength){

	    movement = "-="+features.slideWidth;

      features.slideCur += 1;

    } else {

	    movement = 0;

      features.slideCur = 1;

    }

		break;



		default:

	    movement = 0;

	    features.slideCur = 1;

		break;

	}

	$(features.thumbList).animate({

		left: movement

	}, 300);

	

}





//============================================

// Feature functions

//============================================



// The actual movement of slides

function featureMove(thumbNumber){

  // Declare the feature as "animating", to prevent actions during animation.

	$(features.controls).addClass("animating");

	var thumbCur = $(features.thumbs).filter(".cur");

	var thumbCurIndex = $(features.thumbs).index(thumbCur);

	var thumbNew;

	var thumbNewIndex;

	if (thumbNumber==undefined){

		thumbNew = $(thumbCur).loopNext();

		thumbNewIndex = $(thumbNew).getClassIndex();

	}else if(thumbNumber < 0){

		thumbNew = $(thumbCur).loopPrev();

		thumbNewIndex = $(thumbNew).getClassIndex();

	} else {

		thumbNew = $(features.thumbs).eq(thumbNumber);

		thumbNewIndex = thumbNumber;

	}



  // Specify the currently-visible item.

  var itemCur = {

	  itself: $(features.items).filter(".cur")

	};

	itemCur.desc = $(itemCur.itself).find(".featureDescription");

	itemCur.image = $(itemCur.itself).find("img");

	itemCur.bg =  $(itemCur.itself).find(".featureBackground");



  // Specify the item we WANT to show.	

  var itemNew = {

	  itself: $(features.items).eq(thumbNewIndex)

  };

	itemNew.desc = $(itemNew.itself).find(".featureDescription");

	itemNew.image = $(itemNew.itself).find("img");

	itemNew.bg =  $(itemNew.itself).find(".featureBackground");



	if ($(itemNew.itself).hasClass("featureLoaded")) {

		

	  // If this item is at the end of the thumbSlide (group of thumbs), or at the end of the list, trigger the thumbShift function.

	  /*

		if((((thumbCurIndex+1)/(features.slideCur)==features.slideThumbsLength)||((thumbCurIndex+1)==features.thumbsLength))&&(features.userControl!==true)){

			thumbShift("next",features);

		}

		*/



		$(thumbCur).toggleCur();

		$(thumbNew).toggleCur();



	  // Move our new item to the top, and begin the animation.

		$(itemCur.itself).css("zIndex","100").toggleCur();

		$(itemNew.itself).css({

			"display":"block",

			"zIndex":"75"

			}).toggleCur();

		$(itemNew.desc).hide();

		$(itemCur.image).animate({

			left : "-"+features.itselfWidth

		}, 1000, function(){

	    $(itemCur.image).css("left","0");

			$(itemCur.itself).css("zIndex","50");

			$(itemNew.itself).css("zIndex","100");

				$(features.controls).removeClass("animating");

		});

		$(itemNew.bg).css({

      'display' : 'block'

		}).fadeTo(1,.9);

		$(itemCur.desc).fadeOut(function(){

			$(itemCur.bg).fadeOut();

			$(itemNew.desc).fadeIn();

		});

		features.thumbs.removeClass('lastInSlide');

		features.thumbs.eq((thumbNewIndex+4)%features.thumbs.length).addClass('lastInSlide');

		if(thumbNumber == undefined){

			moveThumb(thumbCur);

		}else if(thumbNumber < 0){

			$(thumbNew).hide(function(){

				$(thumbNew).prependTo(features.thumbList).fadeIn();

			});

		}else{

			var parentSet=$(thumbNew).parent().children();

			var t = $(thumbNew).siblings(":lt("+$(parentSet).index(thumbNew)+")").each(function(){

				moveThumb(this);

				

			});

		}



	} else {
	  killLoop();
	  $(thumbNew).addClass("thumbLoading");	
		$(itemNew.image).load(function(){
		    featureMove(thumbNewIndex);
				$(thumbNew).removeClass("thumbLoading");
				if(thumbNumber === undefined){
					featureLoop();
				}
		});
	}
}

function moveThumb(t){
	$(t).fadeOut(function(){
		$(t).show();
		$(t).appendTo(features.thumbList);
	});
}

var shouldBeSlideCur = Math.floor(Math.random()*features.items.length);
features.items.eq(0).removeClass('cur').addClass('hide');
features.thumbs.eq(0).removeClass('cur').addClass('hide');
features.items.eq(shouldBeSlideCur).addClass('cur').removeClass('hide');
features.thumbs.eq(shouldBeSlideCur).addClass('cur').removeClass('hide');
features.thumbs.removeClass('lastInSlide');
features.thumbs.eq((shouldBeSlideCur+4)%features.thumbs.length).addClass('lastInSlide');
var t = $(features.thumbList).children(":lt("+(shouldBeSlideCur)+")").each(function(){
	moveThumb(this);
});

// Timer for feature carousel - loop indefinitely.
var featureTime;
function featureLoop(){
	clearInterval(featureTime);
	featureTime = setInterval(featureMove,7000,undefined);
}
featureLoop();
