$(document).ready(function(){
	$('.overlay').css('opacity', '0.6');
	$('.overlay').bind('click', function() {
	    	$('.email_form').fadeOut('slow', function () {
	    		$('.overlay').fadeOut('fast');
	    		$('#email_form')[0].reset();
	    		$('#form_errors').removeClass('show');
	    		$('#email-address').removeClass('error');
	    	});
			return false;
		});
	$('#homeSlider').slides({
		preload: true,
		preloadImage: '/images/loading.gif',
		generatePagination: true
	});
	$('#facebookSlider').slides({
		preload: true,
		preloadImage: '/images/loading.gif',
		generatePagination: false
	});
	$('#missionSlider').slides({
		preload: true,
		preloadImage: '/images/loading.gif',
		generatePagination: false
	});			
	$('#mission_slider_show').click(function(){
		$('.mission_cntr').animate({
			top:'361px'
		}, 250, function() {
			$('#mission_slider_show').toggle();
			$('#mission_slider_hide').toggle();
		});
		_gaq.push(['_trackPageview', '/event/did_you_know']);
		return false;
	});
	$('#mission_slider_hide').click(function(){
		$('.mission_cntr').animate({
			top:'507px'
		}, 250, function(){
			$('#mission_slider_hide').toggle();
			$('#mission_slider_show').toggle();
		});
		_gaq.push(['_trackPageview', '/event/did_you_know_close']);
		return false;
	});
	
	$('#email_signup_cta').click(function() {	
		$('.email_form').css({
			top: "115px",
			left : ($(document).width() / 2) - 200
		})
		$('.overlay').fadeIn('fast',function() {
			$('.email_form').fadeIn('slow');
		});
		return false;
	});	
	$('#home_email_submit').click(function () {
	
				//Get the data from all the fields
		var email = $('input[name=email]').val();
		var form_type = $('input[name=signup_type]').val();
		
		//Validation of the form
		//If error found, add error class to the text field
		
		
		if (!email || !((/^([a-z0-9!#$%*/?|^{}`~&'+-=_]+)@[a-z0-9.-]+\.[a-z0-9]{2,}$/i).test(email))){
			$('#email-address').addClass("error");
			$('#form_errors').addClass("show");
			return false;
		}
		else { 
			$('#email-address').removeClass("error"); 
			$('#form_errors').removeClass("show");
		}

		 
		//organize the data properly
		var data = 'email=' + encodeURIComponent(email)+ '&signup_type=' + form_type;

		//show the loading sign
		$('.loading').show();
		 
		//start the ajax
		$.ajax({
		    //this is the php file that processes the data and send mail
		    url: "/process.php",
		     
		    //GET method is used
		    type: "GET",
		
		    //pass the data        
		    data: data,    
		     
		    //Do not cache the page
		    cache: false,
		     
		    //success
		    success: function (html) {             
		        //if process.php returned 1/true 
		        if (html=='1') {
		        	_gaq.push(['_trackPageview', '/event/email/confirm_signup']);   
			    	$('.email_form').fadeOut('slow', function () {
			    		$('.overlay').fadeOut('fast');
			    	});			                       
				//if process.php returned 0/false 
		        } else {
		        	_gaq.push(['_trackPageview', '/event/email/fail_signup']);
		        	$('#form_errors').addClass("show");
		        }              
		    }      
		});
         
        //cancel the submit button default behavior
        
        return false;
    });
    
    $('.close a').click(function() {
    	$('.email_form').fadeOut('slow', function () {
    		$('.overlay').fadeOut('fast');	    		
    		$('#email_form')[0].reset();
	    	$('#form_errors').removeClass('show');
	    	$('#email-address').removeClass('error');
    	});
		return false;
	});

    $('.nav_cta').click(function() {
		$id = $(this).attr('href');
		return false;
 
	});
	/* This code is licensed under Creative Commons Attribution 3.0    *
 * You may share and remix the script so long as you attribute the *
 * original author, Andrew January.                                *
 * http://creativecommons.org/licenses/by/3.0/                     */

    // Check to see if the browser already supports placeholder text (introduced in HTML5). If it does,
    // then we don't need to do anything.
    var i = document.createElement('input');
    if ('placeholder' in i) {
        return;
    }
    
	var isPassword = function(input) {
		return $(input).attr('realType') == 'password';
	}
	
	var valueIsPlaceholder = function(input) {
		return input.value == $(input).attr('placeholder');
	}

	var showPlaceholder = function(input, loading) {
		// FF and IE save values when you refresh the page. If the user refreshes the page
		// with the placeholders showing they will be the default values and the input fields won't
		// be empty. Using loading && valueIsPlaceholder is a hack to get around this and highlight
		// the placeholders properly on refresh.
		if (input.value == '' || (loading && valueIsPlaceholder(input))) {
			if (isPassword(input)) {
				// Must use setAttribute rather than jQuery as jQuery throws an exception
				// when changing type to maintain compatability with IE.
				// We use our own "compatability" method by simply swallowing the error.
				try {
					input.setAttribute('type', 'input');
				} catch (e) { }
			}
			input.value = $(input).attr('placeholder');
			$(input).addClass('placeholder');
		}
	}
	
	var hidePlaceholder = function(input) {
		if (valueIsPlaceholder(input) && $(input).hasClass('placeholder')) {
			if (isPassword(input)) {
				try {
					input.setAttribute('type', 'password');
					// Opera loses focus when you change the type, so we have to refocus it.
					input.focus();
				} catch (e) { }
			}
			
			input.value = '';
			$(input).removeClass('placeholder');
		}
	}
	
	$(':text[placeholder],:password[placeholder]').each(function(index) {
		// We change the type of password fields to text so their placeholder shows.
		// We need to store somewhere that they are actually password fields so we can convert
		// back when the users types something in.
		if ($(this).attr('type') == 'password') {
			$(this).attr('realType', 'password');
		}

		showPlaceholder(this, true);
		
		$(this).focus(function() { hidePlaceholder(this) });
		$(this).blur(function() { showPlaceholder(this, false) });
	});
	if (! ("placeholder" in document.createElement("input"))) {
        $('*[placeholder]').each(function() {
            $this = $(this);
            var placeholder = $(this).attr('placeholder');
            if ($(this).val() === '') {
                $this.val(placeholder);
            }
            $this.bind('focus',
            function() {
                if ($(this).val() === placeholder) {
                    this.plchldr = placeholder;
                    $(this).val('');
                }
            });
            $this.bind('blur',
            function() {
                if ($(this).val() === '' && $(this).val() !== this.plchldr) {
                    $(this).val(this.plchldr);
                }
            });
        });
    }	
});

/*
 *  TABLE OF CONTENTS
 *  
 *  @Initialize
 *  @Events
 *  @AutoInstantiate
 *  @Scrollable
 *  @Stories
 *  @SiteScroll
 *  @TargetBlank
 *  @Keyboard
 *  @Worker Methods
 *
 */
 
/* ---------------------------------- */

/* Initialize */

jQuery(
  
  function ($) {

    $.Body = $('body');
    
    $.Window = $(window);
    
    $.Scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $.Body;
    
    $.Mobile = ($.Body.hasClass('webkit-mobile') || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))),
    
    $.Unsupported = $.Body.hasClass('unsupported-browser');
    
    $.Body
    .Keyboard();
;

    $('[data-controller]').Instantiate();
    $('[data-target=_blank]').TargetBlank();
    
  } 
  
);

/* ---------------------------------- */

/* Events */

(function($) {

  $.Events = {
     
     SECTION_ENTER: 'sectionEnter',
     
     SCROLL_TO: 'scrollTo',
     
     SCROLL: 'windowScroll',
     SCROLL_ENTER: 'windowScrollEnter',
     SCROLL_LEAVE: 'windwScrollLeave',
     
     KEY_UP: 'keyUp',
     KEY_DOWN: 'keyDown',
     KEY_LEFT: 'keyLeft',
     KEY_RIGHT: 'keyRight',
     KEY_ESC: 'keyEsc',
     KEY_SPACE: 'keySpace'
  
  } // Events  
  
  $.Views = {
  
  
  } // Views 

   
  
})(jQuery);


/* ---------------------------------- */

/* Auto Instantiate */

(function($) {

  $.fn.Instantiate = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 

          var $self = $(this),
              $controller = $self.attr('data-controller');
                  
          if ($self[$controller])
            $self[$controller]();
      });
  }
})(jQuery);


/* ---------------------------------- */

/* Shell */

(function($) {

  $.fn.SHELL = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
      this.each(function() { 
 
      });
      return this;
  }

})(jQuery); 

/* ---------------------------------- */
/* Scrollable */

(function($) {

  
  $.fn.Scrollable = function(settings) {
   
     var config = { threshold: -100, offset_scroll: 6, offset_intertia: .15 };
 
     if (settings) $.extend(config, settings);
    
     this.each(function() { 
      
        var $self = $(this),
            $id = $self.attr('id');
            
        config.threshold = 0
        
        if ($.Mobile || $.Unsupported) {  
          $self.css({backgroundAttachment:'scroll'})
        }else{
        
        $.Window
          .bind('scroll',
            function(e){
            
              if ( $.inview($self,{threshold:config.threshold}) ) {
                
                if (!$self.hasClass('_active')){
                
                  $self.addClass('_active');
                  
                  if (config.is_nav)
                    $.Body.triggerHandler($.Events.SECTION_ENTER,$id);
                  
                  $self.triggerHandler($.Events.SCROLL_ENTER);
                  
                }
                  
                _scroll_background();
                  
                $self.triggerHandler($.Events.SCROLL,$.distancefromfold($self,{threshold:config.threshold}) - config.threshold)
                
              }else{
                
                if ($self.hasClass('_active')){
                
                  $self.removeClass('_active');
                  
                  $self.triggerHandler($.Events.SCROLL_LEAVE);
                  
                }
              
              }
              
            
            })
   
        }
        
        function _scroll_background() {

          var _x = '50% '
                  
          var bpos = _x + (-($.distancefromfold($self,{threshold:config.threshold}) - config.threshold) * config.offset_intertia) + 'px';
          
          $self.css({'backgroundPosition':bpos})

        }
        
        /*if (config.auto_scroll)
          _scroll_background();*/
            
     });
     
    return this;
     
  } //Story
 
 

$.fn.Classic = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $id = $self.attr('id'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:true})
     });
     
    return this;
     
  } //Classic 
  
    $.fn.Mission = function() {
   
     this.each(function() { 
     
        var $self = $(this),
        	$id = $self.attr('id'),
            $bg = $self.find('.bg'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:true})
          .bind($.Events.SCROLL,on_scroll)
        
        
          
        function on_scroll(e,distance) {
         
          var bpos = '35% ' + (100+$.Window.height()/2-distance/3) + 'px';
          
          $bg.css({'backgroundPosition':bpos})
          
        }
      
            
     });
     
    return this;
     
  } //Mission
  
  $.fn.SaveTheDate = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $id = $self.attr('id'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:true})

            
     });
     
    return this;
     
  } // save the date
  
 $.fn.Concert = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $id = $self.attr('id'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:false})
            
     });
     
    return this;
     
  } //Concert
   
    
   
  $.fn.Volunteers = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $id = $self.attr('id'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:true})
    });
     
    return this;
     
  } //Volunteers
  
  
  $.fn.Tickets = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $id = $self.attr('id'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:true})
     });
     
    return this;
     
  } //Tickets
  
  
  $.fn.Details = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $id = $self.attr('id'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:true})
  
     });
     
    return this;
     
  } //Event

   
})(jQuery);

/* ---------------------------------- */

/* MainNav */

(function($) {
   $.fn.MainNav = function() {
   
     this.each(function() { 
      
        var $self = $(this),
            $ul = $('<ul/>').appendTo($self),
            $sections = $('[data-nav]'),
            _sections = new Array(),
            $navs = new Array(),
            _active = 0;
            
            
       if (!$.Mobile && !$.Unsupported) { 
        $sections.each(
          function(i){
            _sections.push($(this))
            $('<li/>').appendTo($ul).attr('class','nav_'+$(this).attr('id')).DotNav({id:$(this).attr('id'),name:$(this).attr('data-nav')});
        
          })
       
        }
        
        $.Body
          .bind($.Events.SECTION_ENTER,
            function(e,id){
              
              $sections.each(
                function(i){
                  if ($(this).attr('id')==id)
                    _active = i;
              
                })
            
            })
          .bind($.Events.KEY_RIGHT,
            function(e){
              _active++;
              if (_active>$sections.length-1)
                _active=$sections.length-1;
              _seek();
          })
          .bind($.Events.KEY_LEFT,
            function(e){
              _active--;
              if (_active<0)
                _active=0;
              _seek()
              
          })
          
          
          function _seek() {
            $.Body.triggerHandler($.Events.SCROLL_TO,_sections[_active].attr('id'))
          }
        
            
     });
     
    return this;
     
  } // Main Nav
  
  $.fn.DotNav = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
   
     this.each(function() { 
      
        var $self = $(this),
            $a = $('<a/>'),
            $id = config.id;
            $a
              .attr('href',"#/"+config.name.split(' ').join('_'))
              .attr('class','nav_cta')
              .html($id)
              .appendTo($self)
              .bind('click',
                function(e){
                  
                  $.Body.triggerHandler($.Events.SCROLL_TO,$id)
                  
                  e.preventDefault();
                  
                })
            
            $self
              .attr('data-id',$id);
           
            
        $.Body
          .bind($.Events.SECTION_ENTER,
            function(e,id){
              if (id==$id)
                $self.addClass('active')
              else
                $self.removeClass('active')                        
            });
     });    
    return this;
     
  } // DotNav

    
   
    
})(jQuery);
/* ---------------------------------- */

// Popup window code
function newPopup(url) {
	popupWindow = window.open(
		url,'popUpWindow','height=550,width=680,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}

/* SiteScroll */

(function($) {
   $.fn.SiteScroll = function() {
     this.each(function() { 
      
        var $self = $(this);
            
        $.Body
          .bind($.Events.SCROLL_TO,
            function(e,id){
   
              var $element = $('#'+id),
                  $header = $element.find('header'),
                  _align = $element.attr('data-align'),
                  _offset = $element.attr('data-scrolloffset') ? parseInt($element.attr('data-scrolloffset')) : 50,
                  _top = $element.offset().top;

              if ($header.length>0 && _align!="top") { 
                  
                 // _top = $header.offset().top  + $header.height()/2 - $.Window.height()/2;
                 _top = $element.offset().top - 81;
                  if (_top > $header.offset().top) {
                    _top = $header.offset().top - 50;
                  }
              }
              
              if (_align=="center" && $element.height()>$.Window.height()) {
              
                _top = $element.offset().top + ($element.height()-$.Window.height())/2;
              
              }
              $.Scroll
                .stop()
                .animate(
                  { 'scrollTop': _top },
                  800,
                  'easeInOutQuart'
                )
 
            })
     });
     
    return this;
     
  }
  
})(jQuery);

/* ---------------------------------- */

/* TargetBlank */

(function($) {

   $.fn.TargetBlank = function() {
   
     this.each(function() { 
      
        var $self = $(this);

        $self
        .attr('target','_blank')
        .bind('click',on_click);
        
        function on_click(e){
        
        }
     });
     
    return this;
  }
  
})(jQuery);
    

/* ---------------------------------- */

/* Keyboard */

(function($) {

   $.fn.Keyboard = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
        var $self = $(this);
      
        $(document)
        .bind('keydown',on_keydown);
        
        function on_keydown(e) {
          
          var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
          
          switch(key) {

             
             case 27: //escape

              $.Body.triggerHandler($.Events.KEY_ESC);
                        
             break;
             
             case 32: //space

              $.Body.triggerHandler($.Events.KEY_SPACE);
                        
             break;
             
             case 38: //top
              
              $.Body.triggerHandler($.Events.KEY_UP);
                        
             break;
           
             case 39: //right

              $.Body.triggerHandler($.Events.KEY_RIGHT);
              e.preventDefault();
              
             break;
             
             case 40: ///bottom
            
              $.Body.triggerHandler($.Events.KEY_DOWN);
                        
             break;
              
             case 37: //left
             
              $.Body.triggerHandler($.Events.KEY_LEFT);
                        
             break;
             
             
          }//switch
        }//keydown
      }); 
      return this;
  } 
})(jQuery);


/* ---------------------------------- */

/* Worker */

(function($) {


    $.distancefromfold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return (fold + settings.threshold) - $element.offset().top ;
    };
    
    $.belowthefold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $element.offset().top - settings.threshold;
    };
    
    $.rightoffold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).width() + $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left + $(settings.container).width();
        }
        return fold <= $element.offset().left - settings.threshold;
    };
        
    $.abovethetop = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $element.offset().top + settings.threshold  + $element.height();
    };
    
    $.leftofbegin = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left;
        }
        return fold >= $element.offset().left + settings.threshold + $element.width();
    };
    
    $.inview = function($element, settings) {
        return ($.abovethetop($element,settings)!=true && $.belowthefold($element,settings)!=true)
    };


    $.extend($.expr[':'], {
        "below-the-fold" : "$.belowthefold(a, {threshold : 0, container: window})",
        "above-the-fold" : "!$.belowthefold(a, {threshold : 0, container: window})",
        "right-of-fold"  : "$.rightoffold(a, {threshold : 0, container: window})",
        "left-of-fold"   : "!$.rightoffold(a, {threshold : 0, container: window})"
    });
    
})(jQuery);    
