$(document).ready(function() {


	
	// CND Calendar
	//////////////////////////////////////////////////////////////////////////////////////

	function formulateSlug(slug) {
		slug=slug.replace(/ /g,"-").replace(/[^a-zA-Z0-9\/ -]/g, "");
		slug=slug.toLowerCase();
		return slug;
	} 
		
	// Hold Month Definitions
	var monthArray = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"),
      monthAbbr = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"),
      daysInMonths = [31,28,31,30,31,30,31,31,30,31,30,31];
	
	
	var rightNow = new Date(), // Hold today's datestamp
		weekBegin = new Date(), // Hold beginning of week datestamp (Sunday)
        weekDay = rightNow.getDay(); // Get today's day of the week (0-6)
	
	var cal = $("#thisWeek .bottom table"),
		calLeft = $("#weekOf .left"),
	    calRight = $("#weekOf .right"),
	    wrapMonth = $("#weekOf .middle .wrapMonth"),
		calMonth = $("#weekOf .middle .month"),
		calStart = $("#weekOf .middle .startDate"),
		calEnd = $("#weekOf .middle .endDate"),
		calYear = rightNow.getFullYear();
		
		
		// If a date range is not specified in the markup, use today's date, and figure out the current week based on 
		// the day of the week.
		
		var prevMonth = false;
		var nextMonth = false;
		
		if(calStart.html() == "") { 
		
		var s = rightNow.getDate() - weekDay;

			if(s < 0) {
				
				prevMonth = true;
			}
			
			weekBegin.setDate(rightNow.getDate() - weekDay);  
			calStart.html(weekBegin.getDate()); 
         

		}
		
		if(calEnd.html() == "") { 
		

			weekBegin.setDate(weekBegin.getDate() + 6); 
			calEnd.html(weekBegin.getDate()); 
         
         if(weekBegin.getDate() > 0 && weekBegin.getDate() < 7) {
            nextMonth = true;
         }
			
			if(prevMonth) {
				wrapMonth.html(monthAbbr[weekBegin.getMonth()] + " ");
			} else {
				wrapMonth.html(""); 
			}
		
		}
		
		if(calMonth.html() == "") { 
			
			if(prevMonth) {
				calMonth.html(monthAbbr[rightNow.getMonth() - 1]); 
			} else {
				calMonth.html(monthAbbr[rightNow.getMonth()]); 
			}

		}
      
      
		
		
		// Create date objects for the start date and end date	
		
		var startDate = new Date(calMonth.html() + " " + calStart.html() + ", " + calYear + " 00:00:00");
      
      if(nextMonth) {
      
         var endDate = new Date(monthAbbr[startDate.getMonth() + 1] + " " + calEnd.html() + ", " + calYear + " 00:00:00");
         wrapMonth.html(monthAbbr[endDate.getMonth()] + " ");
         
      } else {
      
         var endDate = new Date(calMonth.html() + " " + calEnd.html() + ", " + calYear + " 00:00:00");
         wrapMonth.html("");
         
      }
      				
		if(prevMonth) { endDate.setMonth(endDate.getMonth() + 1); }	
			
		function loadDays() {
      	   
			$("tr td p", cal).hide("fast").remove();
            		
			var sd = startDate.getFullYear() + '-' + (startDate.getMonth() + 1) + '-' + startDate.getDate(),
				ed = endDate.getFullYear() + '-' + (endDate.getMonth() + 1) + '-' + endDate.getDate(); 
		
			$.post("/inc/ajax-calendar.php", { startDate: sd, endDate: ed },
			   function(data) {
            
				for(var z = 0; z < data.length; z++) {

					var id = jQuery.trim(data[z][0]),
						sd = jQuery.trim(data[z][1]),
						st = jQuery.trim(data[z][2]),
						et = jQuery.trim(data[z][3]),
						el = jQuery.trim(data[z][4]),
						ed = jQuery.trim(data[z][5]);
						
						var sp = sd.split("-"),
							y = sp[0],
							m = sp[1] - 1, // JS starts months with 0
							d = sp[2];
						
						var dayOfWeek = new Date(y,m,d),
							dow = dayOfWeek.getDay();
							
							d = d < 10 ? d.substr(1) : d;
							
							var link = '/events/' + id + '-' + formulateSlug(et); 
							
							$("tr td", cal).eq(dow).append('<p class="event"><a href="' + link + '"><span class="dt">' + (m + 1) + '/' + d + '</span> ' + et + ' (<span class="ti">' + st + '</span>)' + ' @ ' + el + '</a></p>');
							
							$("tr td", cal).eq(dow).find(".event").fadeIn();
                            
				}
				 
			}, "json");
		
		}
				
		
		function shiftDays(d) {
		
			// Advance dates
		
			startDate.setDate(startDate.getDate() + d);
			endDate.setDate(endDate.getDate() + d);	
			
			// Update frontend display
			
			calMonth.html(monthAbbr[startDate.getMonth()]);
			calStart.html(startDate.getDate());
			calEnd.html(endDate.getDate());
			
			// If the range spans multiple months, insert the second month's name,
			// otherwise, clear the second name.
			
			if(startDate.getMonth() == endDate.getMonth()) {
				wrapMonth.html("");
			} else {
				wrapMonth.html(monthAbbr[endDate.getMonth()] + " ");
			}
			
			loadDays();
			
		}
		
		calLeft.click(function() {
		
			shiftDays(-7);
		
		});
		
		calRight.click(function() {
		
			shiftDays(7);
		
		});
		
		
		loadDays();
		
	
	// Remove right-side borders from last cells
	$("th:last", cal).addClass("last");
	$("td:last", cal).addClass("last");
	

	
});





	


// CND Image Slider
//////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function() {


		
	var cndSlider = $("#slider"), // DIV that contains slider Images
	info = $("#sliderInfo"),
	menu = $("#sliderMenu"),
	scroll = $("#sliderScroll"),
	up = $("#up"),
	down = $("#down"),
	delay = 10000, // Delay between automatic advancement
	cndCnt = 0, // Initialize Counter
	cndVisible = 0, // Default visible image (index)
	interval = null,
	changing = false;
	  
	  
	function onChange() {

		changing = false;
		
		var alt = $("img", cndSlider).eq(cndVisible).attr("alt"),
			text = $("img", cndSlider).eq(cndVisible).attr("data-text"),
            link = $("img", cndSlider).eq(cndVisible).attr("link");
			
			text = text.substring(0,330);
		
		$("h2", info).html(alt);
		$("p", info).html(text);
        
        console.log(link);
        
        if(link.length > 0){
            $("a", info).attr("href",link).text(alt);
            $("h2", info).html("<a href=" + link + ">" + alt + "</a>");
        } else {
            $("a", info).removeAttr("href");
            $("h2 a", info).removeAttr("href");
        }
        
     // scroll.animate({ scrollTop: $(".menuItem").eq(cndVisible).offset().top}, 500 );

	}    

	function setMenu() {

	
	} 
							  
		  
	function nextPic() {
		
		changing = true;
		  
			
			$("img", cndSlider).eq(cndVisible).fadeOut("slow", function() {  // Hide current image before advancing
				  

				// If we've reached the end, wrap back to the beginning
				if((cndVisible+1) == cndCnt) { var feq = 0; } else { var feq = (cndVisible+1); }
			  
				cndVisible = feq; // Set index of new visible image
				setMenu(); 
					
				// Bring in next image
				$("img", cndSlider).eq(feq).fadeIn("slow", function() {
										  
					onChange(); // Refresh information panel
				  
				}); 
				  
	  
				  
			});
			
									   
									   
	}    
		  
		  
	  
	// Count Slider Images
	$("img", cndSlider).each(function(i,v) {
		  
		cndCnt++;
		  
		// Show default image
		if(i == cndVisible) {
			$(this).show();
		}
		
	var alt = $("img", cndSlider).eq(i).attr("alt"),
		source = $("img", cndSlider).eq(i).attr("src"),
		text = $("img", cndSlider).eq(i).attr("data-text");
		
		text = text.length > 85 ? text.substring(0, 85) + "..." : text;
		
		$(".menuItem .img").eq(i).append('<img src="' + source + '" alt="' + alt + '" />');
		$(".menuItem p").eq(i).html(text);
		  
	});
	  
	  

					  
	if(cndCnt > 1) {  // Only setup timer if there are multiple images loaded
   
   
      if(cndCnt > 3) {
      
         down.click(function() { 
         
           scroll.animate({ scrollTop: scroll.scrollTop() + 83}, 500 );
         
         });
         
         up.click(function() { 
         
           scroll.animate({ scrollTop: scroll.scrollTop() - 83}, 500 );
         
         });

      
      }
	
		$(".menuItem").each(function(i,v) {
		
			$(this).click(function() {
			
				//window.location = $("img", cndSlider).eq(i).attr("data-url");
			
			});
			
			$(this).hover(function() {
			
				if(!changing && i != cndVisible) {
			
				clearInterval(interval);
								
						changing = true;
													
							$("img", cndSlider).eq(cndVisible).hide();  // Hide current image before advancing
								  
								//If we've reached the end, wrap back to the beginning
								if((i) == cndCnt) { var feq = 0; } else { var feq = (i); }
							  
								cndVisible = feq; // Set index of new visible image
								setMenu(); 
									
								//Bring in next image
								$("img", cndSlider).eq(feq).show();
																							
								onChange(); // Refresh information panel
					
							
				}
			
			}, function() {
			
				
				clearInterval(interval);
				interval = setInterval(nextPic, delay); // Set timer
				
				
			
			});
			
			
		});
		  
		  
		  
		interval = setInterval(nextPic, delay); // Set timer
		onChange();  // Initialize information panel
		  
	}
	
	
	  
	 
	// This will stop the slideshow when the window/tab is not focused, 
	// and then it will start again when the window/tab is focused.
	  
	var blurred = false; 
		
	$(window).focus(function(){
	  
		if(blurred) {
			setTimeout(function() { nextPic(); }, delay);
		}
		  
	});
	  
	$(window).blur(function(){
	  
		 blurred = true;
		 clearInterval(interval);
		   
	});
		
		
});
