KA = {
	activities: {
		index: function() {
			$script(['/javascripts/kidsahead/raphael-min.js', '/javascripts/common/carousel.min.js'], function() {
				KA.ArticleCarousel.init();
			});
		},
		
		show: function() {
			KA.common.comments();
		}
	},
	
	articles: {
		index: function() {
			$script(['/javascripts/kidsahead/raphael-min.js', '/javascripts/common/carousel.min.js'], function() {
				KA.ArticleCarousel.init();
			});
		},

		show: function() {
			KA.common.comments();
		}
	},
	cool_jobs: {
			index: function() {
				$script(['/javascripts/kidsahead/raphael-min.js', '/javascripts/common/carousel.min.js'], function() {
					KA.ArticleCarousel.init();
				});
			},
	
			show: function() {
				//KA.common.comments();
			}
		},
	
	common: {
		comments: function() {
			var $comments = $( "div#comments" ),
				$repliers = $( "div.reply a", $comments ),
				$reporters = $( "form.flag-comment", $comments ),
				$textarea = $( "form#comment-form textarea" );
			
			$reporters.bind( "submit", function() {
				return confirm( "Are you sure you want to flag this comment as inappropriate?" );
			});
			
			$repliers.bind( "click", function() {
				$textarea.focus().val( "@" + $repliers.attr( "data-reply-to" ) + " " ).focus();
				
				return false;
			});
		},
		
		init: function() {
			// Enable placeholder attribute
			$( "input, textarea" ).placehold();
			
			// Handle login and register buttons
			$( "a.lightbox" ).bind( "click", function() {
				var $this = $( this );
				
				$.ajax({
					dataType: "html",
					method: "get",
					success: function( rsp ) {
						if ( rsp !== null ) {
							UTIL.lightbox.init( $this, rsp );
						}
					},
					url: $this.attr( "href" )
				});
				
				return false;
			});
			
			// Get In Touch form
			$( "form#get-in-touch" ).bind( "submit", function() {
				var $form = $( this ),
					$inputs = $( "input, textarea", $form ),
					$message = $( "p.error-message", $form ),
					is_valid = true;
				
				$message.hide();
				
				
				$inputs.removeClass( "has-error" ).not("#feedback_details").each( function() {
					var $input = $( this );
					
					if ( !$input.val() ) {
						$input.addClass( "has-error" );
						$message.show();
						
						is_valid = false;
					}
				});
				
				return is_valid;
			});
			
			// Take A Chance! spinner
			$( "a#take-a-chance-anchor" ).bind( "click", function() {
				var $anchor = $( this ),
					$container = $anchor.parent(),
					current_bg_y = parseFloat( $container.css( "background-position" ).split( " " )[1] );
				
				$.ajax({
					beforeSend: function() {
						setInterval( function() {
							$container.css( "background-position", "0 " + ( current_bg_y += 40 ) + "px" );
						}, 22 );
					},
					dataType: "json",
					method: "get",
					success: function( rsp ) {
						if ( rsp !== null && rsp.url ) {
							window.location = rsp.url;
						}
					},
					url: $anchor.attr( "href" )
				});
				
				return false;
			});
			
			// Preload the gigantic background images
			setTimeout( function() {
				UTIL.imagePreloader( "/images/kidsahead/layout/stub-header.jpg", function( img ) {
					$( "div#stub-header" ).css( "background-image", 'url("' + img.src + '")' ).fadeIn( "slow" );
				});
				
				UTIL.imagePreloader( "/images/kidsahead/layout/stub-footer.jpg", function( img ) {
					$( "div#stub-footer" ).css( "background-image", 'url("' + img.src + '")' ).fadeIn( "slow" );
				});
			}, 1000 );
		}
	},
	
	events: {
		index: function() {
			$( "span.has-event" ).parent().addClass( "has-event" );
		},
	
		show: function() {
			var $venue = $( "li#event-location[data-lat]" ),
				$location = $( "span.locality[data-lat]", $venue );
			
			if ( $venue.length ) {
				var venue_lat = $venue.attr( "data-lat" ),
					venue_lng = $venue.attr( "data-lng" ),
					location_lat = $location.attr( "data-lat" ),
					location_lng = $location.attr( "data-lng" );
				
				$( "div#event-gmap" ).googleMap({
					center: [location_lat, location_lng],
					markers: [{ lat: venue_lat, lng: venue_lng }],
					image: {anchor: [20, 54],origin: [0, 0],size: [41, 57],url:"/images/kidsahead/layout/gmap-marker.png"}
				});
			}
		}
	},
	
	external: {
		show: function() {
			var $bar = $( "div#reader-bar-outer" ),
				bar_height = $bar.outerHeight(),
				$iframe = $( "iframe#reader-content" );
			
			$iframe.css( "height", $( window ).height()  - bar_height );
			
			$( window ).bind( "resize", function() {
				$iframe.css( "height", $( window ).height()  - bar_height );
			});
		}
	},
	
	locations: {
		index: function() {
			var locations = [],
				$container = $( "div#gmap-container" ),
				$list = $( "ul#locations-list" ),
				$items = $( "li.location", $list );
			
			$items.each( function() {
				var $item = $( this );
				
				locations.push({
					content: '<div class="gmap-infowindow">' + $item.html() + '</div>',
					lat: $item.attr( "data-lat" ),
					lng: $item.attr( "data-lng" ),
					title: $.trim( $item.find( "h2" ).text() )
				});
			});

			$( "div#gmap" ).googleMap({
				markers: locations,
				image: {anchor: [20, 54],origin: [0, 0],size: [41, 57],url:"/images/kidsahead/layout/gmap-marker.png"}
			});
			
			UTIL.enhance.nthChild( "html.ie ul#locations-list li.location:nth-child(4n+1)", "nth-child" );
		},
		
		show: function() {
			var locations = [],
				$location = $( "sup#location-state" ),
				$container = $( "div#gmap-container" ),
				$list = $( "ul#venues-list" ),
				$items = $( "li.venue", $list );
			
			$items.each( function() {
				var $item = $( this );
				
				locations.push({
					content: '<div class="gmap-infowindow">' + $item.html() + '</div>',
					lat: $item.attr( "data-lat" ),
					lng: $item.attr( "data-lng" ),
					title: $.trim( $item.find( "h4.entry-title" ).text() )
				});
			});

			$( "div#gmap" ).googleMap({
				center: [$location.attr( "data-lat" ), $location.attr( "data-lng" )],
				markers: locations,
				zoom: 12,
				image: {anchor: [20, 54],origin: [0, 0],size: [41, 57],url:"/images/kidsahead/layout/gmap-marker.png"}
			});
			
			UTIL.enhance.nthChild( "html.ie div.content-listing li.hentry:nth-child(2n+1)", "nth-child" );
		}
	},
	
	pages: {
		homepage: function() {
			var $promo = $( "div#coolest-promo" ),
				$slides = $( "li", $promo ),
				$announcementBar = $("#announcement-banner"),
				$announcementClose = $("#announcement-close");
			
			$slides.not( ":first" ).hide();
			
			$promo.show( 0, function() {
				var i = setInterval( function() {
					var $slide = $slides.filter( ":visible" ),
						curr_index = $slide.index(),
						max = $slides.length,
						next_index = ( ( curr_index + 1 ) == max ) ? 0 : curr_index + 1;

					$slide.fadeOut( "slow", function() {
						$( $slides.get( next_index ) ).fadeIn( "slow" );
					});
				}, 8000 );
			});
			
			// Close accouncement bar and set cookie
			$announcementClose.click(function(e) {
				e.preventDefault();

				// Build and set cookie to expire after one month
				var date = new Date();
				date.setTime(date.getTime()+(30*24*60*60*1000));
				var expires = "; expires=" + date.toGMTString();

				document.cookie = "ka_announcement_" + $announcementBar.data("announcement") + "=dismissed" + expires + "; path=/";
				$announcementBar.slideUp(100);
			});
			
			var $subjects_container = $( "div#subjects-promo" ),
				$subjects = $( "li", $subjects_container ),
				$controls = $( "a.control", $subjects_container ),
				$next = $( "a.next", $subjects_container ),
				$prev = $( "a.prev", $subjects_container ),

				// promo controls
				changeSubjects = function(dir, event){
					
					if (event) {
						var evt = event || window.event; // IE compatibility
						evt.preventDefault ? evt.preventDefault() : evt.returnValue = false;
					}

					var $curr = $subjects.filter( ".current" ),
						$to_change_to = $curr.looparound(dir),
						$next = $to_change_to.looparound("next"),
						$prev = $to_change_to.looparound("prev");
					
					$subjects.each(removeClasses);

					$next.addClass( "next" );
					$prev.addClass( "prev" );
					$to_change_to.addClass( "current" );

					_gaq.push( $to_change_to.attr( "data-track-event" ).split( "," ) );

				},
				removeClasses = function(){
					$(this).removeClass( "current" ).removeClass( "next" ).removeClass( "prev" ); 
				};
				nextSubject = function(event){
					changeSubjects("next", event);
				},
				prevSubject = function(event){
					changeSubjects("prev", event);
				},
			
				// auto rotation
				subjectTimer = null,
				startTimer = function(){
					subjectTimer = setInterval(nextSubject, 6000);
				},
				clearTimer = function(){
					clearInterval(subjectTimer)
				};

			$next.click(nextSubject);
			$prev.click(prevSubject);
			$subjects_container.hover(clearTimer, startTimer);
			startTimer();

		}
	},
	
	subjects: {
		index: function() {
			
			// Load slider-dependent file and execute
			$script('/javascripts/common/slider.min.js', function() {
				KA.SubjectDragger.init();
			});
		},
		show: function() {
			UTIL.enhance.nthChild( ".ie #promoted-content .promoted-item:nth-child(2n+1)", "nth-child" );
		}
	}
};

UTIL = {
	enhance: {
		nthChild: function( selector, className ) {
			return $( selector ).addClass( className );
		}
	},
	
	exec: function( controller, action ) {
		var ns = KA,
			action = ( action === undefined ) ? "init" : action;
		
		if ( controller !== "" && ns[controller] && typeof( ns[controller][action] ) == "function" ) {
			ns[controller][action]();
		}
	},
	
	imagePreloader: function( image_path, callback ) {
		var img = document.createElement( "img" );
		
		if ( arguments.length == 2 && typeof( callback ) == "function" ) {
			img.onload = function() {
				callback( img );
			};
		};
		
		img.setAttribute( "src", image_path );
	},
	
	init: function() {
		var body = document.body, controller = body.getAttribute( "data-controller" ), action = body.getAttribute( "data-action" );
		
		UTIL.exec( "common" );
		UTIL.exec( controller );
		UTIL.exec( controller, action );
	},
	
	lightbox: {
		hide: function( lightbox, curtain ) {
			lightbox.fadeOut( "fast", function() {
				curtain.fadeOut( "slow", function() {
					lightbox.remove();
					curtain.remove();
				});
			});
		},
		
		init: function( elem, content ) {
			var $curtain = $( '<div id="lightbox-curtain" />' ),
				$lightbox = $( '<div id="lightbox-wrapper" />' ),
				$closer = $( '<a href="" id="lightbox-close" />' );
			
			elem.blur();
			
			$( "body" ).append( $curtain ).append( $lightbox );
			
			$curtain.css({
				height: $( document ).height()
			}).bind( "click", function() {
				UTIL.lightbox.hide( $lightbox, $curtain );
			});
			
			$lightbox.html( content ).css({
				left: ( $( window ).width() - $lightbox.outerWidth() ) / 2,
				top: $( window ).scrollTop() + 75
			});
			
			$closer.bind( "click", function() {
				UTIL.lightbox.hide( $lightbox, $curtain );
				return false;
			}).prependTo( $lightbox );
			
			UTIL.lightbox.show( $lightbox, $curtain );
		},
		
		show: function( lightbox, curtain ) {
			curtain.fadeIn( "fast", function() {
				curtain.css({
					filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)"
				});
				
				lightbox.fadeIn( "slow", function() {
					$( ":text:visible:first", lightbox ).focus();
				});
			});
		}
	}
};

$().ready( UTIL.init );

