// ============================
// 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 ();
		 }
	};
	
	//============================================
	// Replace HRs with Divs for styling
	//============================================
	$("hr").each(function() {
		var hrClass = $(this).attr("class");
		$(this).wrap("<div class='hr " + hrClass +"'></div>");
	});
	
	//============================================
	// Input focus and blur
	//============================================
	$("input, textarea", $("form")).focus(function(){
		$(this).addClass("focus");
		$(this).parents(".form-field").toggleCur();
	});
	$("input, textarea", $("form")).blur(function(){
		$(this).removeClass("focus");
		$(this).parents(".form-field").toggleCur();
	});
		
	//============================================
	// Place .inField labels into their respective fields, remove the text on click
	//============================================
	$("label.inField").each(function(){
		var thisFieldName=$(this).attr("for");
		var thisText=$(this).text();
		var thisField=$("input[name="+thisFieldName+"]");

		$(this).hide();
		$(thisField).val(thisText).data("originalValue",thisText);

		$(thisField).focus(function(){
			var originalValue=$(this).data("originalValue");
			var currentValue=$(this).val();
			if(originalValue==currentValue){
				$(this).val("");
			}
		});
		$(thisField).blur(function(){
			var originalValue=$(this).data("originalValue");
			var currentValue=$(this).val();
			if(currentValue===''){
				$(this).val(originalValue);
			}
		});
	});
		
	//============================================
	// Expanding List - hides and expands a smaller list to any LI with the class of "expandingList"
	//============================================
	$(".expandingList").addClass("expandingList-active").find("ul").hide();
	$(".expandingList-active .title").click(function(){
		var targetUl=$(this).parent().find("ul");
		if($(targetUl).is(":hidden")){
			$(targetUl).fadeIn();
			$(this).parent().addClass("expandingList-open");
		} else {
			$(targetUl).fadeOut();
			$(this).parent().removeClass("expandingList-open");
		}
	});
	
	//============================================
	// Cycle footer media
	//============================================
	$("#section-media .listMedia").after("<a href='#' id='mediaPrev' class='mediaNav' rel='prev'>Previous</a><a href='#' id='mediaNext' class='mediaNav' rel='next'>Next</a>");
	
  $(".mediaNav").live("click", function(){
    var direction=$(this).attr("rel");
    clearInterval(mediaTime);
	  mediaMove(direction);
	  return false;
  });
	
	//============================================
	// subNavs
	//============================================
	$(".subNav .header a").click(function(){
		var theOtherOne=$(this).parents(".subNav").siblings(".subNav");
		$(theOtherOne).children(":not(.header)").hide();
		$(theOtherOne).find(".open").removeClass("open");
		if($(this).hasClass("open")){
		  $(this).removeClass("open");
		  $(this).parent().siblings().hide();	
		} else {
		  $(this).addClass("open");
		  $(this).parent().siblings().show();
		
			$(".subNav").hover(function(){
				clearTimeout(menuTimeout);
			}, function(){
				menuTimeout = setTimeout(function(){
					  $(".subNav li:not(.header)").hide();
					  $(".subNav .open").removeClass("open");
				  }, 3000);
			});
		}
	});
	
	
	
	//============================================
	// 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");
	  	}
	  /* $(this).append('<a href="#" class="closeAlert">Close this alert</a>');*/
	});
	$(".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);
	});
	
	
  // Add classes that affect the caption style.
  /*
	$(features.thumbs).eq(features.slideThumbsLength).addClass("noHover");

	$(features.thumbs).each(function(i){
		d   = (i + 1)/(features.slideThumbsLength );
		d_i = parseInt(d, 10);
		if((d == d_i) && (i !== 0)) {
			$(this).addClass("lastInSlide");
		}
	});
	*/

  // 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;
  });
	
	
  // ======================================	
	// .listPage to set up content-pager
  // ======================================
	$(".listPager").each(function(){
		
		// Figure out how many "groups" of page items there will be, when divided by the PageBy title.
    function countGroups(pageBy,itemTotal){
	    var groupsTotal=Math.ceil(itemTotal/pageBy);
	    return groupsTotal;
    }
    function getRemainder(pageBy,itemTotal){
	    var itemRemainder=itemTotal%pageBy;
	    return itemRemainder;
    }

		var pageTitle=$(this).attr("title"); // Get the title string
		var pageByString=pageTitle.replace("PageBy",""); // Get the "page by" value out of the title string
		var pageBy=parseFloat(pageByString); // Convert the "page by" value to a number
    var itemTotal=$(this).find("li").length; // Count the items
    var groupsTotal=countGroups(pageBy,itemTotal); // Count how many groups we'll have
    var itemRemainder=getRemainder(pageBy,itemTotal); // Count how many items will be in the last group
    var pagerContents=""; // Create the empty pagerContents variable
		var pagerClass;
		var pageEnd;
		for(i=1;i<=groupsTotal;i=i+1){
			var pageStart=((i*pageBy)-pageBy)+1;
			if(i==groupsTotal){
				if(itemRemainder>1){
			    pageEnd="-"+(parseFloat(((i-1)*pageBy)+itemRemainder)); 
			    } else if(itemRemainder == 0){
			      pageEnd="-"+(parseFloat(((i-1)*pageBy)+2));
				} else {
				  pageEnd=""; 
				}
			} else {
			  pageEnd="-"+(pageBy*i); 
			}
			if(i==1){
				pagerClass="cur";
			} else {
				pagerClass="none";
			}
			// Loop, filling the pagerContents variable with LIs
		  pagerContents=pagerContents+"<li class='"+pagerClass+"'><a href='#'>"+pageStart+pageEnd+"</a></li>";
		}

    // Place the pagerContents
    var pagerNav=("<ul class='pagerNav'>"+pagerContents+"</ul>");
		$(this).before(pagerNav);
		
    // Onclick, use the index of the clicked item to figure out which group to display
		$(".pagerNav a").click(function(){
			if($(this).parent().hasClass("cur")){
				
			} else {
			  var thisParent=$(this).parent();
				var targetNumber=$(this).parent().getIndex()+1;
				var targetPager=$(this).closest("ul").next();
					
				$(targetPager).find("li:visible").fadeOut(function(){
          var maxIndex=(targetNumber*pageBy)-1;
          var minIndex=(((targetNumber*pageBy)-pageBy));
		        $(targetPager).children("li").each(function(){
              var thisIndex=$(this).getIndex();
			        if((thisIndex<=maxIndex)&&(thisIndex>=minIndex)){
				        $(this).fadeIn();
		        	}
	        	});
				});
				$(this).parent().toggleCur().siblings(".cur").toggleCur();
		  	return false;
			}
		});
	});

	// ======================================	
	// Search box (clear on click)
	// ======================================
	$('#search-inHeader input.text').one('click', function(){
		$(this).attr('value', '');
	});

	
});

//============================================
// Media functons
//============================================

function mediaMove(direction){
	$("#section-media .listMedia").children("li:visible").fadeOut(function(){
		if (direction == "prev") {
		  $(this).loopPrev().fadeIn();
		} else {
		  $(this).loopNext().fadeIn();
		}
	});
}

// Make the footer-media items loop indefinitely
var mediaTime;

function mediaLoop(){
	mediaTime = setInterval(mediaMove,5000);
}

mediaLoop();



//============================================
// 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);
	
	// Add classes that affect the caption style.
	/*
	$(features.thumbs).each(function(i){
		range_low  = ((features.slideCur - 1)  * features.slideThumbsLength);
		range_high = (range_low + features.slideThumbsLength - 1);
		if((i < range_low) || (i > range_high)) {
		  $(this).addClass("noHover");
		} else {
		  $(this).removeClass("noHover");
		}
	});
	*/

}




//============================================
// 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);
			/*
			$(thumbCur).fadeOut(function(){
//				$(itemNew.itself).appendTo($('#featureContent'));
				$(thumbCur).show();
				$(thumbCur).appendTo(features.thumbList);
			});
			*/
		}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);
});

//if(shouldBeSlideCur > 1){
//	for(var i=1; i<shouldBeSlideCur; i++){
//		thumbShift('next', features);
//	}
//}

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


//============================================
// Cookie Plugin
// Copyright (c) 2006 Klaus Hartl (stilbuero.de)
// Dual licensed under the MIT and GPL licenses:
// http://www.opensource.org/licenses/mit-license.php
// http://www.gnu.org/licenses/gpl.html
//============================================

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};