/*
 *Coded by Lucas Bonner.
*/
$(window).load(function() {
	$("body").removeClass("nojs");
	
	if ( $("#searchForm").length ) {
		var regBGcolor = $("#searchText").css('background-color');
		var regValue = $("#searchText").val();
		$("#searchText").click(function() {
			var regBGcolor = $("#searchText").css({ 'background-color': '#ffffff' });
			$("#searchText").select();
		})
		$("#searchText").blur(function() {
			if ( $("#searchText").val() == '' || $("#searchText").val() == regValue ) {
				if ( $("#searchText").val() == '' )
					$("#searchText").val(regValue);
				$("#searchText").css({ 'background-color': regBGcolor });
			}
		})
	}
	
	if ( $("#rightColumn").length ) {

		// Cycle through the children in the right Column
		$(function() {
			// Settings
			var container = $("#rightColumn .children");
			var slider = $("#rightColumn .slider");
			var panels = new Array();
			panels['cur'] = 1;
			panels['next'] = 2;
			var duration = 1000;
			
			// Dynamic Settings
			panels['total'] = $(slider).children().size() / 2;
			var movingDistance = new Array();
			var buttons = "<ul style='width:"+ (panels['total'] * 17) +"px;'>\n";
			for (var i=1; i <= panels['total']; i++) {
				// Create buttons for jumping to a panel
				var buttons = buttons + "<li><a href='#"+ i +"'>"+ i +"</a></li>\n";
				
				// Find and save the height of each panel.
				var child1 = (i * 2) - 1;
				var child2 = i * 2;
				child1 = $(slider).children(".child:nth-child("+child1+")").outerHeight(true);
				child2 = $(slider).children(".child:nth-child("+child2+")").outerHeight(true);
				movingDistance[i] = child1 + child2;
			};
			$(container).data("moving", false);
		
			// Add buttons
			buttons = buttons + "</ul>\n";
			$(container).children(".arrowUp, .arrowDown").append(buttons);
			$(container)
				.find(".arrowUp li:nth-child(1) a, .arrowDown li:nth-child(1) a")
					.css("background-color", "#5C595C");
			$(container).css("height", (movingDistance[1] + 60) + "px");

			function change(panel) {
				if ( $(container).data("moving") == false ) {
					$(container).data("moving", true);
					$("#rightColumn .arrowUp li:nth-child("+panels['cur']+") a").css("background-color", "#3D393C");
					$("#rightColumn .arrowDown li:nth-child("+panels['cur']+") a").css("background-color", "#3D393C");
					
					// Reset the interval call if not called by the interval,
					// which is indicated by a null value in panel
					// and define or clean up the value of panel.
					if ( panel == null ) {
						panel = panels['next'];
					} else {
						clearInterval(interval);
						// Set automatic progression
						interval = setInterval(function(){
							change(null)
						}, 25000);
						
						panel = parseInt(panel.split('#')[1]);
					}
				
					if ( panel > panels['total'] ) { panel = 1; }
					if ( panel == panels['cur'] ) {
						$(container).data("moving", false);
						return false;
					} else if ( panel > panels['cur'] ) {
						var move = parseInt(slider.css("top"));
						for (var i=panels['cur']; i < panel; i++) {
							move = move - movingDistance[i];
						};
					} else {
						var move = parseInt(slider.css("top"));
						for (var i=panels['cur']-1; i >= panel; i--) {
							move = move + movingDistance[i];
						}
					}
					var moveDuration = ( panel > (panels['cur']+2) || panels < (panels['cur']-2) ) ? duration * 2 : duration;
					$(container)
						.stop()
						.animate({
							"height": movingDistance[panel] + 60
						}, {
							duration : moveDuration,
							easing : 'linear'
						});
					$(slider)
						.stop()
						.animate({
							"top": move
						}, {
							duration : moveDuration,
							easing : 'linear',
							complete : function() {
								$(container).data("moving", false);
							}
						});
					panels['cur'] = panel;
					$("#rightColumn .arrowUp li:nth-child("+panels['cur']+") a").css("background-color", "#525053");
					$("#rightColumn .arrowDown li:nth-child("+panels['cur']+") a").css("background-color", "#525053");
					panels['next'] = panels['cur'] == panels['total'] ? 1 : panels['cur']+1;
				}
			}
			
			//Set links to respond...
			$("#rightColumn .arrowUp a").click(function(event){
				change($(this).attr('href'));
				event.preventDefault();
			});	
			$("#rightColumn .arrowDown a").click(function(event){
				change($(this).attr('href'));
				event.preventDefault();
			});
			
			// Set automatic progression
			var interval = setInterval(function(){
				change(null)
			}, 25000);
		})
	
		if ( $("body").is(".page-id-51") ) {
			$(function() {
				// Most common elements accessed.
				var amount = $("input[name=amount]");// The amount radio inputs.
				var other = $("#other");// The #other amount radio.
				var otherAmount = $("#otherAmount");// The #otherAmount <input> text field.
				var designate = $('#for');// The #for <select> field.
				var designatePrev = '';// The #for <select> field.
				var	designation = $("#designate .sub");// Returns a <ul> with designation field
				var dedicate = $("input[name=dedicate]");// The dedicate radio inputs.
				var dedicateTo = $("#dedicateTo");// The #dedicateTo <textarea>
				
				// Initial Changes
				if ( amount.filter(":checked").val() != "other" ) {
					otherAmount.attr("readonly", true);
					otherAmount.attr("value", "Select an Amount");
				}
				if ( designate.val() != 'cs' && designate.val() != 'ms' ) {
					designation.hide("fast");
				}
				if ( dedicate.filter(":checked").length == 0) {
					dedicateTo.attr("readonly", true);
				}
				
				
				// Amount and otherAmount changes.
				amount.change(function() {
					if ( amount.filter(":checked").val() == "other" ) {
						otherAmount.removeAttr("readonly");
						otherAmount.attr("value", "$50.00");
						otherAmount.select();
					} else {
						otherAmount.attr("readonly", true);
						otherAmount.attr("value", "Select an Amount");
					}
				})
				otherAmount.click(function() {
					if ( other.filter(":checked").val() != "other" ) {
						other.attr("checked", "checked");
						other.trigger('change');
					}
				})
								
				// Designation changes.
				designate.change(function() {
					if ( designate.val() == 'cs' ) {
						if ( designatePrev != 'ms' ) {
							designation.find("textarea").text("Enter the name of the Child you wish to sponsor.");
							designation.animate({
								height: 'toggle',
								opacity: 'toggle'
							},
							'slow', function() {
								designation.find("textarea").select();
							});
						} else {
							designation.find("textarea").select();
						}
						designatePrev = 'cs';
					} else if ( designate.val() == 'ms' ) {
						if ( designatePrev != 'cs' ) {
							designation.find("textarea").text("Enter the name of the Child you wish to sponsor.");
							designation.animate({
								height: 'toggle',
								opacity: 'toggle'
							},
							'slow', function() {
								designation.find("textarea").select();
							});
						} else {
							designation.find("textarea").select();
						}
						designatePrev = 'ms';
					} else {
						if ( designatePrev == 'cs' || designatePrev == 'ms' ) {
							designation.animate({
								height: 'toggle',
								opacity: 'toggle'
							},
							'slow', function() {
								designation.find("textarea").select();
							});
						}
						designatePrev = designate.val();
					}
				})
				
				// Dedication changes.
				dedicate.change(function() {
					if ( dedicate.filter(":checked").length != 0 ) {
						dedicateTo.removeAttr("readonly");
						dedicateTo.select();
					}
				});
				dedicateTo.click(function() {
					if ( dedicate.filter(":checked").length == 0 ) {
						dedicate.first().attr("checked", true);
						dedicate.trigger('change');
					}
				});
				dedicateTo.blur(function() {
					if ( dedicateTo.val() == "" || dedicateTo.val() == "Person's Name" ) {
						dedicate.filter(":checked").removeAttr("checked");
						dedicateTo.attr("readonly", true);
						dedicateTo.val("Person's Name");
					}
				})
				
			})
		}
		
	} else if ( $("#oneColumn").length ) {
		
		// The slider...
		$(function() {
	
			var panels = new Array();
			panels['total']		= $(".slider").children().size();
			// panels['next'] defined later, will contain the next panel.
			panels['curID'] = 'panel_2';//Contains the current panel.
			panels['cur'] = ( parseFloat($("#currentPanel").val()) >= 1 ) ? parseFloat($("#currentPanel").val()) : 2;//Contains the current panel.
			panels['divide'] = 0;//	contains where 0 is in panels['cur'] relative to panels['total'].
			panels['next'] = null;//Contains the current panel.
			panels['nextID'] = null;//Contains the current panel.
						
			var regMozRadius		= $(".hentry").css("-moz-border-radius");
			var regWebkitRadius		= $(".hentry").css("-webkit-border-radius");
			var regRadius			= $(".hentry").css("border-radius");
			var regBorderBottom		= $(".hentry").css("border-bottom-width");
			var regHeight			= $(".hentry").css("height");
			var regOp				= $(".hentry").css("opacity");
			var regWidth			= $(".hentry").css("width");
			var regImgWidth			= $(".hentry img.wp-post-image.landscape").css("width");// For Landscape
			var regImgHeight		= $(".hentry img.wp-post-image.portrait").css("height");// For Portrait
			var regSponsorPos		= -200;
	
			var movingDistance	    = 250;
	
			var curRadius			= 10;
			var curBorderBottom		= 1;
			var curHeight			= new Array();
			curHeight[0]			= '100%';
			var curOp				= 1;
			var curWidth			= 300;
			var curImgWidth			= 300;// For Landscape images
			var curImgHeight		= 300;// For Portrait images
			var curSponsorPos		= 4;

			var $thePanels			= $('#oneColumn .slider > div');
			var $container			= $('#oneColumn .slider');
			
			var duration			= 1500;
    
			$("#oneColumn").data("currentlyMoving", false);

			function returnToNormal(element) {
				$(element)
					.animate({
						MozBorderRadius: regMozRadius,
						WebkitBorderRadius: regWebkitRadius,
						borderRadius: regRadius,
						borderBottom: regBorderBottom,
						height: regHeight,
						opacity: regOp,
						width: regWidth
						},
						duration)
					.find("a.sponsor")
						.animate({
							right: regSponsorPos
							}, (duration+"").substring(0, (duration+"").length-1) * 9)
						.end()
				if ( $(element +" img.wp-post-image").is(".landscape") ) {
					$(element +" img.wp-post-image").animate({ width: regImgWidth }, duration)
				} else {
					$(element +" img.wp-post-image").animate({ height: regImgHeight }, duration)
				}
			}
	
			function growBigger(element) {
				var height = curHeight[element.substr(1)] ? curHeight[element.substr(1)] : curHeight[0];
				$(element)
					.animate({
						MozBorderRadiusBottomleft: curRadius,
						MozBorderRadiusBottomright: curRadius,
						WebkitBorderBottomRightRadius: curRadius,
						WebkitBorderBottomLeftRadius: curRadius,
						borderBottomLeftRadius: curRadius,
						borderBottomRightRadius: curRadius,
						borderBottomWidth: curBorderBottom,
						height: height,
						opacity: curOp,
						width: curWidth
						},
						duration)
					.find("a.sponsor")
						.animate({
							right: curSponsorPos
							}, (duration+"").substring(0, (duration+"").length-1) * 9)
						.end()
				if ( $(element +" img.wp-post-image").is(".landscape") ) {
					$(element +" img.wp-post-image").animate({ width: curImgWidth }, duration);
				} else {
					$(element +" img.wp-post-image").animate({ height: curImgHeight }, duration);
				}
				if ( $.browser.msie && height != '100%' ) {
					$("#oneColumn").animate({ marginBottom: (height - $("#oneColumn").height()) }, duration);
				}
			}
			
			// direction true = right || false = left;
			// show true = show || false = hide;
			function toggleReadMore(direction, show) {
				var arrow = (direction) ? '.arrowRight' : '.arrowLeft';
				var showBg = (direction) ? "-24px -1px" : "-52px -1px"; 
				var hideBg = (direction) ? "2px -1px" : "-78px -1px"; 
								
				if ( show ) {
					$(arrow)
						.click(function(){ change(direction); })
						.animate({
							backgroundPosition: showBg
						})
						.find(".more")
							.animate({
								bottom: 0,
								opacity: 1
								});
				} else {
					$(arrow)
						.unbind()
						.animate({
							backgroundPosition: hideBg
						})
						.find(".more")
							.animate({
								bottom: -50,
								opacity: 0
								});
				}
				
			}

			// Get the next/previous set of posts
			// getPosts: 'next' || 'prev'
			// lastID should contain either the first or the last id
			//	 that's in use for panel id's
			function getMorePosts(link, getPosts, lastID) {
				$.get( link, {
					'getPosts' : getPosts,
					'lastID' : lastID,
					'ajax' : 1
					}, function(data) {
						
						// Get the proper height of each panel
						$("#oneColumn").append("<div class='temp' style='overflow: hidden; width: 0;'>"+ data +"</div>");
						var $elements = $("#oneColumn .temp div.hentry");
						var input = $("#oneColumn .temp input");
						$elements.each(function( index ) {
							var ID = $(this).attr('id');
							if ( ID.substr(6,1) == 'b' )
								panelNum = parseFloat('-'+ ID.substr(7));
							else
								panelNum = parseFloat(ID.substr(6));
							
							// if ( $(this).is(".landscape") ) {
							// 	$(this).css('width', curImgWidth);
							// } else {
								$(this).find("img.wp-post-image").css('height', curImgHeight);
							// }
							$(this)
								.css({
									'border-bottom-width': curBorderBottom,
									'height': curHeight[0],
									'width': curWidth
									})
							
							curHeight[ID] = $(this).height();
					
							if ( $(this).find("img.wp-post-image").is(".landscape") ) {
								$(this).find("img.wp-post-image").css('height', 'auto');
							} else {
								$(this).find("img.wp-post-image").css('height', regImgHeight);
							}
							$(this)
								.css({
									'border-bottom-width': regBorderBottom,
									'height': regHeight,
									'width': regWidth
								})
								
						})// End .each()
							
							panels['total'] += $elements.length;
							switch ( getPosts ) {
								case 'prev':
									panels['divide'] += $elements.length;
									$container
										.css({
											"left": parseFloat($container.css('left')) - ($elements.length * movingDistance),
											"width": parseFloat($container.css('width')) + ($elements.length * movingDistance)
										})
										.prepend($elements);
									toggleReadMore(false,true);
									break;
								case 'next':
									$container
										.css("width", parseFloat($container.css('width')) + ($elements.length * movingDistance))
										.append($elements);
									toggleReadMore(true,true);
									break;
							}// End switch ( input.attr('id') )
							
							// Set the new current Panel
							panels['cur'] = panels['next'];
							// Update events.
							updateEvents();
							
							$("#oneColumn .temp").remove();
							
					}, 'html')// End $.get();
					
			}//End getMorePosts();

			function updateEvents(current) {
				var panel = new Array();
				
				if ( panels['cur'] > 0 ) {
					
					//Next panel
					panel[0] = panels['cur'] + 1;
					//Previous Pan
					panel[1] = panels['cur'] - 1;
							
				// If -1 or 0
				} else if ( panels['cur'] >= -1  ) {
					//Next panel
					panel[0] = panels['cur'] + 1;
					//Previous Panel
					panel[1] = "b"+ ( (panels['cur'] - 1) + '').substr(1);
				
				// else it's less than -1
				} else {
					//Next Panel
					panel[0] = "b"+ ( (panels['cur'] + 1) + '').substr(1);
					//Previous Panel
					panel[1] = "b"+ ( (panels['cur'] - 1) + '').substr(1);
				}
				
				//remove all previous bound functions
				$("#panel_" + panel[0]).unbind();	
				//go forward
				$("#panel_" + panel[0]).click(function(event){
					change(true);
					event.preventDefault();
				});
	
	            //remove all previous bound functions															
				$("#panel_" + panel[1]).unbind();
				//go back
				$("#panel_" + panel[1]).click(function(event){
					change(false);
					event.preventDefault();
				});
	
				//remove all previous bound functions
				if ( panels['cur'] >= 0 )
					$("#panel_" + panels['cur']).unbind();
				else
					$("#panel_b" + (panels['cur'] + '').substr(1)).unbind();
				
			}

			//direction true = right, false = left
			function change(direction) {
				
			    //if not at the first or last panel
				if ( (direction && !(panels['cur'] <= (panels['total'] - panels['divide']) ) ) || (!direction && !(panels['cur'] > (panels['total'] - panels['divide']) - panels['total']) ) ) { return false; }
				
				panels['next']	= direction ? panels['cur'] + 1 : panels['cur'] - 1;
				if ( panels['next'] >= 0 ) {
					panels['nextID'] = "#panel_"+ panels['next'];
				} else {
					panels['nextID'] = "#panel_b"+ (panels['next']+'').substr(1);
				}
				if ( panels['cur'] >= 0 ) {
					panels['curID'] = "#panel_"+ panels['cur'];
				} else {
					panels['curID'] = "#panel_b"+ (panels['cur']+'').substr(1);
				}
				
				if ( $(panels['nextID']).is(".end") ) { return false; }
				        
		        //if not currently moving
		        if (($("#oneColumn").data("currentlyMoving") == false)) {
            
					$("#oneColumn").data("currentlyMoving", true);
			
					var leftValue	= $(".slider").css("left");
					var movement	= direction ? parseInt(leftValue, 10) - movingDistance : parseInt(leftValue, 10) + movingDistance;
		
					$(".slider")
						.stop()
						.animate({
							"left": movement
						},
						duration,
						function() {
							$("#oneColumn").data("currentlyMoving", false);
	
							// Controls getting more children and showing or hiding the read more.
							// if we're going to whats currently the very first panel.
							if ( panels['next'] == ((panels['divide'] - panels['total']) + panels['total']) - (panels['divide'] * 2) + 1 ) {
								
								if ( $(panels['nextID'] +" input.prev_posts").val() != '' ) {
									getMorePosts( $(panels['nextID'] +" input.prev_posts").val(), 'prev', ((panels['divide'] - panels['total']) + panels['total']) - (panels['divide'] * 2) + 1 );
								} else {
									// Set the new current Panel
									panels['cur'] = panels['next'];
									// Update events.
									updateEvents();
								}

							// If we're going to what's currently very the last panel.
							} else if ( panels['next'] == panels['total'] - panels['divide'] ) {
								if ( $(panels['nextID'] +" input.next_posts").val() != '' ) {
									getMorePosts( $(panels['nextID'] +" input.next_posts").val(), 'next', panels['total'] - panels['divide'] );
								} else {
									// Set the new current Panel
									panels['cur'] = panels['next'];
									// Update events.
									updateEvents();
								}
							} else {
								// Set the new current Panel
								panels['cur'] = panels['next'];
								// Update events.
								updateEvents();
							}
						});
						
					// if we're going to whats currently the very first panel.
					if ( panels['next'] == ((panels['divide'] - panels['total']) + panels['total']) - (panels['divide'] * 2) + 1 ) {
						toggleReadMore(false,false);
					// If we're leaving what's currently the very first panel.
					} else if ( panels['next'] == ((panels['divide'] - panels['total']) + panels['total']) - (panels['divide'] * 2) + 2 && panels['cur'] == ((panels['divide'] - panels['total']) + panels['total']) - (panels['divide'] * 2) + 1 ) {
						toggleReadMore(false,true);
					} 
					// If we're going to what's currently very the last panel.
					if ( panels['next'] == panels['total'] - panels['divide'] ) {
						toggleReadMore(true,false);
					// If we're leaving what's currently the very last panel.
					} else if ( panels['next'] == ((panels['total'] - panels['divide']) - 1) && panels['cur'] == (panels['total'] - panels['divide']) ) {
						toggleReadMore(true,true);
					}

					growBigger(panels['nextID']);
					returnToNormal(panels['curID']);
					
				}
			}
			
			// Get the proper height of each panel
			$("#oneColumn").append("<div class='temp' style='overflow: hidden; width: 0;'></div>");
			$thePanels.each(function( index ) {
				var ID = $(this).attr('id');
				var tmpID = 'tmp_'+ $(this).attr('id');
				$(this).clone(false)
					.attr('id', tmpID)
					.appendTo("#oneColumn .temp");
			var element = $('#'+ tmpID);
			// if ( $(element).find('img').is(".landscape") ) {
			// 	$(element).find('img').css({
			// 		'height': 3,
			// 		'width': curImgWidth
			// 	});
			// } else {
				$(element).find('img.wp-post-image').css('height', curImgHeight);
			// }
			$(element)
				.css({
					'border-bottom': curBorderBottom,
					'height': curHeight[0],
					'width': curWidth
				})
			curHeight[ID] = $(element).height();
			if ( index == $thePanels.length-1 )
				$("#oneColumn .temp").remove();
			
			});
			
			switch ( true ) {
				// Set Next Panel
				case (panels['cur'] < panels['total']):	
					$("#panel_"+(panels['cur'] + 1)).click(function(event){ event.preventDefault();  change(true);});
	
					//when the right arrows are clicked
					$(".arrowRight").click(function(){ change(true); });	
	
					$(window).keydown(function(event){
					  switch (event.keyCode) {
							case 32: //space
								$(".arrowRight").click();
								break;
							case 39: //right arrow
								$(".arrowRight").click();
								break;
					  }
					});
												
				// Activate previous panel
				case (panels['cur'] == panels['total']):
					if (panels['cur'] == panels['total'] )
						toggleReadMore(true,false);
										
					
					$("#panel_"+(panels['cur']-1)).click(function(event){ event.preventDefault(); change(false); });

					//when the left arrows are clicked
					$(".arrowLeft").click(function(){ change(false); });
					
					$(window).keydown(function(event){
					  switch (event.keyCode) {
						    case 37: //left arrow
								$(".arrowLeft").click();
								break;
					  }
					});
				
				case (panels['cur'] > panels['total']):
				
					if (panels['cur'] > panels['total'] ) {
						panels['cur'] = panels['total'];
						toggleReadMore(false,false);
						toggleReadMore(true,false);
						var leftValue	= $(".slider").css("left");
						var movement = parseInt(leftValue, 10) + (movingDistance * panels['cur']);
						$container.animate({
							'left': movement
						}, duration)
					}
						
					growBigger("#panel_"+panels['cur']);
					
			}
					
		});
		
	}
});


