(function($, window, document, undefined) {

var galleryItems = $('#home-gallery-contents .home-gallery-item'),
	imgCount     = galleryItems.length,
	imgIndex     = 0,
	nextImgIndex = imgIndex + 1;

	
	// ===============
	// = main object =
	// ===============
	var	teachHere = {
		ready: function() {
			this.navFAQ();
			this.placeholders();
			this.contactForm();
			this.newsletterForm();
			this.buildGalleryNav();
			this.anchorScroll();
			this.startShow();
			this.galleryVideos();
			this.minHeight();
		},
		gallery_timer: null,
		
		/** Bind nav and FAQ functionality */
		navFAQ: function() {
			$('<a id="nav-clone"/>').appendTo('body');
			$('#nav ul li a, .secondary-nav ul li a').click(function(e) {
				var href = $(this).attr('href');
				if ( window.location.pathname === "/" && (/\/#/.test( href )) ) {
					$.scrollTo(href, 700);
					return false;
				}
			});
			
			// Start all answers hidden
			$('#faq ul li span.answer').hide();
			
			// Toggle showing answers
			$('#faq ul li').toggle(function() {
				$(this).addClass('expanded').find('span.answer').show(300);
			}, function() {
				$(this).removeClass('expanded').find('span.answer').hide(300);
			});
			
			// Share link and share links div hover
			$('div.share a').hover(function() {
				$(this).parent('div.share').prev('div.share-links').show();
			}, function() {
				$(this).parent('div.share').prev('div.share-links').hide();
			});
			
			$('div.share-links').hide().hover(function() {
				$(this).show();
			}, function() {
				var $link = $(this);
				setTimeout(function () { $link.hide(); }, 1500);
			});
			
		},
		
		placeholders: function() {
			var inputs = $('input:text');
			inputs.each(function() {
				var input = $(this);
				var defaultText = input.val();
				input.focus(function() {
					if(input.val() == defaultText) { input.val(''); }
				});
				input.blur(function() {
					if($.trim(input.val()) == '') { input.val(defaultText); }
				});
			});
		},
		
		/** Send contact form with AJAX */
		contactForm: function() {
			$("form#contact-form").submit(function(ev) {
				var form = this;
				ev.preventDefault();
				$.ajax({  
					type: form.method,
					url: form.action,
					data: $(form).serialize(),
					dataType: "json",
					success: function(data) {
						if (data.status === "error") {
							$(form).replaceWith( $(data.html).find("form") );
							teachHere.contactForm();
						} 
						else {
							$(form).replaceWith('');
							$('.rt-confirmation_message, .c-confirmation').show();
						}
					}
				});
			});
		},
		
		/** Send newsletter form with AJAX */
		newsletterForm: function() {
			$("form#newsletter-form").submit(function(ev) {
				var form = this;
				ev.preventDefault();
				$.ajax({  
					type: form.method,	
					url: form.action,  
					data: $(form).serialize(),	
					dataType: "json",
					success: function(data) {  
						if (data.status == "error") {
							$(form).find("input").not(':hidden').css({"border":"#FF0000 1px solid"});
						} else {
							$(form).replaceWith('<div id="newsletter-confirm">Your information has been submitted.</div>');
						}
					},
					error: function(data) {
					  alert('Communication error: ' + data.status + '\nPlease try again later.');
					}
				});
			});
			$("form#newsletter-form input").focus(function(ev) {
				$(this).attr("value", "");
			});
		},
		
		/** Build the Gallery Hero Nav */
		buildGalleryNav: function() {
			var htmlString = '';
			$('#home-gallery-contents div.home-gallery-item').each(function(index) {
				var i = index+1;
				htmlString += '<a class="gallery-nav-link" href="#'+i+'">'+i+'</a>';
			});
			$('#home-gallery-nav span').replaceWith(htmlString);
			$('#home-gallery-nav a:eq(0)').addClass('active');
		},
		
		/** Blog ticker */
		moveTicker: function() {
			$('#blog-ticker').scrollable().next();
		},
		
		/** Splash Hero */
		nextSlide: function() {

			$('div.home-gallery-item').
				eq(nextImgIndex).fadeIn(500).end().
				eq(imgIndex).fadeOut(500);
			
			$('#home-gallery-nav a').removeClass('active').
				eq(nextImgIndex).addClass('active');
			
			nextImgIndex = nextImgIndex + 1;
			imgIndex = imgIndex + 1;
			if(nextImgIndex == imgCount){
				nextImgIndex = 0;
			}
			if(imgIndex == imgCount){
				imgIndex = 0;
			}
		},

		anchorScroll: function() {
		  // smooth scroll on anchor changes
      $('a[href^="' + window.location.pathname + '#"],a[href^="#"]').click(function(event){
        //prevent the default action for the click event
        event.preventDefault();

        //get the full url - like mysitecom/index.htm#home
        var full_url = this.href;
        
        //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
        var parts = full_url.split("#");
        var trgt = parts[1];
        
        //get the top offset of the target anchor
        var target_offset = $("#"+trgt).offset();
        var target_top = target_offset.top;

        //goto that anchor by setting the body scroll top to anchor top
        var hash    =   window.location.hash.replace(/^#!?/, '');
        if(!hash.length) {
            hash    =   'home';
        }
        var toGo    =   Math.abs($('#' + hash).offset().top - target_top),
            len     =   Math.ceil(toGo / 1000.0) * 200;
        if(len < 1000) {
            len     =   1000; // make sure it's at least one second
        }
        $('html, body').animate({'scrollTop':target_top}, len, function() {
            window.location.hash    =   trgt;
        });
      });
		  
		},
		
		/** Initialize the blog ticker and Splash Hero */
		startShow: function() {

			$("#blog-ticker").scrollable({
				size: 1,
				items: '.bs-snippet',
				loop: true,
				clickable: false,
				keyboard: false
			});
			
			var ticker_timer = setInterval( teachHere.moveTicker, 6000 );
			
			// Image Gallery Splash
			$('div.home-gallery-item').hide().eq(0).show();
			if ( imgCount > 1 )
				teachHere.gallery_timer = setInterval( teachHere.nextSlide, 8000 );
			
			// Click Handlers for ticker
			$('span.bs-next a').click(function() {
				$('#blog-ticker').scrollable().next();
				window.clearInterval( ticker_timer );
				ticker_timer = setInterval( teachHere.moveTicker, 6000 );
				return false;
			});
			$('span.bs-prev a').click(function() {
				$('#blog-ticker').scrollable().prev();
				window.clearInterval( ticker_timer );
				ticker_timer = setInterval( teachHere.moveTicker, 6000 );
				return false;
			});
			
			// Click handlers for gallery
			$('a.gallery-nav-link').click(function(e) {
				var nl = $(this),
					i  = nl.index();
				$('.iframe-wrapper .close').click();
				$('div.home-gallery-item')
					.eq( i ).fadeIn( 500 ).end()
					.eq( imgIndex ).fadeOut( 500 );
				
				$('#home-gallery-nav a').removeClass('active').
					eq(i).addClass('active');
				
				imgIndex = i;
				nextImgIndex = i + 1;
				if ( nextImgIndex === imgCount ) {
					nextImgIndex = 0;
				}
				if ( imgIndex === imgCount ) {
					imgIndex = 0;
				}
				window.clearInterval( teachHere.gallery_timer );
				teachHere.gallery_timer = setInterval( teachHere.nextSlide, 8000 );
				return false;
			});
		},
		galleryVideos: function() {
		    var videoLinks  =   $('.home-gallery-image a[href*=vimeo.com]');
		    if(!videoLinks.length) { return; }
		    var _iframe     =   $('<iframe />'),
		        wrapper     =   $('<div class="iframe-wrapper" />'),
		        close       =   $('<a href="#close" class="close">&times;</a>');
		    wrapper.hide().appendTo('body').append(close).css({'left': videoLinks.eq(0).offset().left, 'top': videoLinks.eq(0).offset().top - videoLinks.eq(0).find('img').height()});
		    videoLinks.each(function() {
		        var videoLink   =   $(this),
		            videoID     =   parseInt( videoLink.attr('href').replace(/[^\d]+/g, ''), 10 ),
		            iframe      =   _iframe.clone();
		        iframe.attr({
		            'src':  'http://player.vimeo.com/video/' + videoID + '?title=0&amp;byline=0&amp;portrait=0"',
		            'width': 640,
		            'height': 400,
		            'scrolling': 'false',
		            'frameborder': 0
		        });
		        videoLink.click(function(c) {
		            c.preventDefault();
    				window.clearInterval( teachHere.gallery_timer );
		            wrapper.find('iframe').remove();
		            wrapper.append(iframe);
		            wrapper.show();
		        });
		    });
		    close.click(function(c) {
		        c.preventDefault();
		        wrapper.find('iframe').remove();
		        wrapper.hide();
				teachHere.gallery_timer = setInterval( teachHere.nextSlide, 8000 );
		    });
		},
		minHeight: function() {
		    var targetHeight    =   $(window).height(),
		        sections        =   $('body > div:has(.section-content)');
		    sections.each(function() {
		        var section     =   $(this),
		            minHeight   =   targetHeight - parseFloat(section.css('padding-top')) - parseFloat(section.css('padding-bottom'));
		        if( section.is('#home') ) {
		            var snippets    =   $('#blog-snippets'),
		                callouts    =   $('#home-callouts');
		            callouts.attr('data-padding-bottom', parseFloat(callouts.css('padding-bottom')));
		            minHeight   =   targetHeight - (callouts.position().top + callouts.outerHeight());
		            if(minHeight > 0) {
		                callouts.css({
		                    'padding-bottom': (parseFloat(callouts.attr('data-padding-bottom')) + minHeight) + 'px'
		                });
		            } else {
		                callouts.css({
		                    'padding-bottom': callouts.attr('data-padding-bottom') + 'px'
		                });
		            }
		        } else if(section.is('#who-apply') || section.is('#grades-seven')) {
		            // pass
		        } else {
		            section.css({
    		            'min-height':   minHeight + 'px',
    		            '_height':      minHeight + 'px'
    		        });
		        }
		    });
		    // this part moves the page to compensate for the changes in min-heights
            var hash    =   window.location.hash.replace(/^#!?/, '');
            if(hash.length) {
                setTimeout(function() {
                    var target  =   $('[id="' + hash + '"], [name="' + hash + '"]');
                    $('html,body').scrollTop(target.offset().top);
                }, 100);
            }
		}
	};
	
	// Start it up
	$(document).ready(function () { teachHere.ready.call( teachHere ); });
	
	$(window).bind('resize load', teachHere.minHeight);
	
	$(window).bind('hashchange', function() {
	    var hash    =   window.location.hash.replace(/^#!?/, '');
        if(hash.length) {
            var target  =   $('[id="' + hash + '"], [name="' + hash + '"]');
            $('html,body').scrollTop(target.offset().top);
        }
	});

})(jQuery, this, this.document);

/** usage: log('inside coolFunc',this,arguments); */
window.log = function () {
	log.history = log.history || [];
	log.history.push( arguments );
	if ( this.console ) {
		console.log( Array.prototype.slice.call( arguments ) );
	}
};
/** Debug in all browsers */
window.debug = function () {
	debug.history = debug.history || [];
	debug.history.push( arguments );
	if ( this.console ) {
		console.debug( Array.prototype.slice.call( arguments ) );
	}
};
/** Dir for objects */
window.dir = function () {
	if ( this.console ) {
		console.dir( arguments );
	}
};

// catch all document.write() calls
(function(doc){
	var write = doc.write;
	doc.write = function(q){
		log('document.write(): ', arguments);
		if (/docwriteregexwhitelist/.test(q)) write.apply( doc, arguments );
	};
})(document);
