(function($) {
	__active_section = this.__active_section = null;
	
	var Event = this.Event = {
		bindWindowEvents: function() {
			$(window).unbind('resize').resize(function() {
				Popover.fixPosition();
			});
		},
		bindNavEvents: function() {
			if($.browser.msie && $.browser.version < 7)
				return;
			
			$('#navigation li')
				.removeClass('highlight')
				.find('a')
				.append('<span class="hover" />').each(function () {
				var __section = $(this).text().toLowerCase();
				var is_active_section = !!__active_section && __active_section == __section;
				var $span = $('> span.hover', this).css('opacity', is_active_section ? 1.0 : 0.0);
				
				if(is_active_section)
					$(this).find('span.hover').addClass('current_page');
				
				$(this).hover(
					function () { $span.not('.current_page').stop().fadeTo(400, 1.0); },
					function () { $span.not('.current_page').stop().fadeTo(400, 0.0); }
				);
			});
		},
		bindPopoverEvents: function() {
			if(!$('.enablePopover').length)
				return;
				
			$('.enablePopover').unbind('click').click(function() {
				var info = $(this).attr('class');
				var source_type = (info.match(/(container|url)/))[0];
				var source = (info.match(new RegExp(source_type + ':([^\s]+)')))[1];

				$dither = $('<div>').attr({ id: 'dither' }).css({ opacity: 0.0 });
				$popover = $('<div>').attr({ id: 'popover' }).css({ opacity: 0.0 })
					.append($('<div>').addClass('close').html($('<a>').attr({ href: '#' }).text('Close')))
					.append($('<div>').addClass('content'));
				$('body').append($popover).append($dither);
				$('#dither').fadeTo(400, 0.6);
				$('#popover').fadeTo(400, 1.0);
				
				$('#popover .close, #dither').unbind('click').click(function() {
					$('#popover, #dither').fadeTo(400, 0.0, function() {
						$(this).remove();
					});
					return false;
				});

				switch(source_type) {
					case 'container':
						$('#popover .content').html($(this).siblings('.container').html());
						if($(this).siblings('.container').html().indexOf('timeline') >= 0){
							$('#popover .content').css({width: '990px'});
						} else{
							$('#popover .content').css({width: '600px'});
						}
						Popover.fixPosition();
						//$('#popover, #dither').css({ display: 'block' });
					break;
					case 'url':
						$loading = $('<div>').addClass('ui-loadmsg');
						$popover.append($loading);
						$('#popover .content').css({width: '600px'});
						Popover.fixPosition();
						
						$.ajax({
							url: source,
							type: 'post',
							complete: function(response) {
								$popover.html($(response.responseText));
							}
						});
					break;
				}
				
				$('#popover .content form').unbind('submit').submit(function(){
					var message = '';
					
					if(!$("#popover .content form #email").val().match(/^([a-z]+[\w-]*\.?)+@([\w-]+\.)+[a-z]{2,4}$/i)){
						message += "Please enter your email address.<br />";
					}
					if($("#popover .content form #name").val() == ''){
						message += "Please enter your name.<br />";
					}
					if($("#popover .content form #address").val() == ''){
						message += "Please enter your address.<br />";
					}
					if($("#popover .content form #city").val() == ''){
						message += "Please enter your city.<br />";
					}
					if($("#popover .content form #state").val() == ''){
						message += "Please enter your state.<br />";
					}
					if($("#popover .content form #zip").val() == ''){
						message += "Please enter your Zip code.<br />";
					}
					if($("#popover .content form #phone").val() == ''){
						message += "Please enter your phone number.<br />";
					}
					
					if(message != ''){
						$errormessage = $('<div>').html("The following errors have occured:<br /><br />" + message + "<br />");
						$('input[type=submit]').before($errormessage);
					} else {
						var checkvals = '';
						
						if($('#popover .content form #newsevents:checked').length > 0){
							checkvals += '1';
						} else {
							checkvals += '0';
						}
						
						if($('#popover .content form #programs:checked').length > 0){
							checkvals += '1';
						} else {
							checkvals += '0';
						}
						
						if($('#popover .content form #education:checked').length > 0){
							checkvals += '1';
						} else {
							checkvals += '0';
						}
						
						if($('#popover .content form #support:checked').length > 0){
							checkvals += '1';
						} else {
							checkvals += '0';
						}
						
						if($('#popover .content form #volunteers:checked').length > 0){
							checkvals += '1';
						} else {
							checkvals += '0';
						}
						
						$.ajax({
							url: '/newsletter.php',
							type: 'post',
							data: 'checkvalues=' + checkvals + '&email=' + $('#popover .content form #email').val() + '&name=' + $('#popover .content form #name').val() + '&address=' + $('#popover .content form #address').val() + '&city=' + $('#popover .content form #city').val() + '&state=' + $('#popover .content form #state').val() + '&zip=' + $('#popover .content form #zip').val() + '&phone=' + $('#popover .content form #phone').val(),
							success: function(msg){
								$('#popover .content').html('Thank you for your interest in The Smith Center');
							}
						});
					}
					
					return false;
				});
				
				return false;
			});
		},
		bindPopupEvents: function() {
			if(!$('.enablePopup').length)
				return;
				
			$('.enablePopup').unbind('click').click(function() {
				var info = $(this).attr('class');
				var url = (info.match(/url:([^\s]+)/))[1];
				var width = (info.match(/width:(\d+)/))[1];
				var height = (info.match(/height:(\d+)/))[1];
				
				window.open(url, 'SCpop', 'status=0, resizable=1, scrollbars=1, width=' + width + ', height=' + height);
				return false;
			});
		},
		bindFaqEvents: function() {
			$('#faq li a').unbind('click').click(function() {
				var $div = $(this).siblings('.faq-container');

				if($(this).hasClass('open')) {
					$div.animate({ height: 0 }, { queue: false, duration: 300 });
					$(this).removeClass('open');
				} else {
					$div.animate({ height: $div.find('.faq-copy').outerHeight() }, { queue: false, duration: 300 });
					$(this).addClass('open');
				}
				
				return false;
			});
		},
		bindNewsEvents: function() {
			$('.newsletter-link').unbind('click').click(function() {
				var $div = $(this).parent().siblings('.newsletter-container');

				if($(this).hasClass('open')) {
					$div.animate({ height: 0 }, { queue: false, duration: 300 });
					$(this).removeClass('open');
				} else {
					$div.animate({ height: $div.find('.newsletter-copy').outerHeight() }, { queue: false, duration: 300 });
					$(this).addClass('open');
				}
				
				return false;
			});
		},
		bindFormEvents: function() {
			if(!$('.enableFormValidation').length)
				return;
				
			$('.enforceDataType').keyup(function() {
				var __type = $(this).attr('datatype');
				var __value = $(this).val();
				
				switch(__type) {
					case 'int':
					case 'integer':
						if(!(/^\d*$/.test(__value)))
							$(this).val(__value.replace(/[^\d]/g, ''))
					break;
					case 'nsc':
					case 'nospecialchars':
						if(!(/^[a-z0-9\s]$/i.test(__value)))
							$(this).val(__value.replace(/[^\d]/g, ''))					
					break;
					case 'dec':
					case 'decimal':
					case 'cur':
					case 'currency':
						if(!(/^([\d]*\.)?\d*$/.test(__value)))
							$(this).val(__value.replace(/[^\d\.]/g, ''))
					break;
				}
			});
			$('.validateInPlace').blur(function() {
				var __type = $(this).attr('datatype');
				var __values, __value = $(this).val();
				var $error_container, __should_append;
				
				__should_append = /^\*/.test($(this).attr('errorcontainer'));
				$error_container = $($(this).attr('errorcontainer').replace(/^\*/, ''));
				
				switch(__type) {
					case 'int':
					case 'integer':
						if(/^\d*$/.test(__value))
							return $(this).removeClass('ui-form-invalid_value');
							
						$(this).addClass('ui-form-invalid_value');	
						$(this).siblings('.ui-error-container').text('Please use only numbers (0-9).');
					break;
					case 'nsc':
					case 'nospecialchars':
						if(/^[a-z0-9\s]$/i.test(__value))
							return $(this).removeClass('ui-form-invalid_value');
							
						$(this).addClass('ui-form-invalid_value');
						$(this).siblings('.ui-error-container').text('You may not use special characters - only A-Z, 0-9, and spaces.');	
					break;
					case 'dec':
					case 'decimal':
					case 'cur':
					case 'currency':
						if(/\./.test(__value)) {
							__value = __value.replace(/[^\d\.]/g, '');
							if(/^\./.test(__value))
								__value = '0' + __value;
							if(/\.$/.test(__value))
								__value = __value + '00';
								
							__values = __value.split('.');
							$(this).val(__value);
						} else {
							__values = __value.split('.');
							$(this).val(!!__value ? (__value + '.00') : '0.00');
						}

						var __num_valid = 0;
						for(var i = 0; i < __values.length; i++)
							if(!!__values[i])
								__num_valid++;
								
						if(!!__num_valid)
							return $(this).removeClass('ui-form-invalid_value');
							
						$(this).addClass('ui-form-invalid_value');
						$(this).siblings('.ui-error-container').text('You must specify a dollar amount greater than $0.00.')
					break;
				}
			});
			$('.validatePresence').blur(function() {
				if(!!$(this).val())
					return;
							
				__should_append = /^\*/.test($(this).attr('errorcontainer'));
				$error_container = $($(this).attr('errorcontainer').replace(/^\*/, ''));
					
			});
			$('.enableSelectConditionalValidation').change(function() {
				var __value = $(this).val();
				var $target = !!$(this).attr('dependent') ? $($(this).attr('dependent')) : $(this).parent().siblings('.conditional');
				$target.css({ display: __value.match(/other/i) ? 'block' : 'none' });
			});
			$('.enableBooleanConditionalValidation').change(function() {
				__value = $(this).val();
				var $target = !!$(this).attr('dependent') ? $($(this).attr('dependent')) : $(this).parent().siblings('.conditional');
				$target.css({ display: $(this).is(':checked') || $(this).is(':selected') ? 'block' : 'none' });
			});
		}
	};
	
	var Popover = this.Popover = {
		fixPosition: function() {
			var w_width, w_height;
			var $popover = $('#popover');
			var $content = $('#popover .content');
			
			if(!$popover.length)
				return;
				
			w_width = $(document).width() > $(window).width() ? $(document).width() : $(window).width();
			w_height = $(document).height() > $(window).height() ? $(document).height() : $(window).height();	

			$('#dither').css({ width: w_width, height: w_height });				

			if($content.outerHeight() > 500)
				$content.css({ height: 500 });
			
			if($content.html().indexOf('timeline') > 0){
				$popover.css({
					marginLeft: -($content.outerWidth() * 0.5),
					top: "100px"
				});
				window.scrollTo(0,0);
			} else {
				$popover.css({
					marginLeft: -($content.outerWidth() * 0.5),
					top: $(window).scrollTop() + ($(window).height() * 0.5) - ($content.outerHeight() * 0.5)
				});
			}
		}
	};
	
	var Flash = this.Flash = {
		place: function() {
			if($('#building_the_dream').length)
				swfobject.embedSWF('/building_the_dream.swf', 'building_the_dream', '700', '407', '9.0.0', '/flash/expressInstall.swf');
			if($('#timeline').length)
				swfobject.embedSWF('/ElegantXmlTimeline/deploy/elegant_timeline.swf', 'timeline', '1000', '600', '9.0.0', '/flash/expressInstall.swf');
			if($('#multimedia').length)
				swfobject.embedSWF('/multimedia.swf', 'multimedia', '700', '407', '9.0.0', '/flash/expressInstall.swf');
			if($('#photo_gallery').length)
				swfobject.embedSWF('/education.swf', 'photo_gallery', '700', '407', '9.0.0', '/flash/expressInstall.swf');
			if($('#construction').length)
				swfobject.embedSWF('/construction.swf', 'construction', '700', '407', '9.0.0', '/flash/expressInstall.swf');
			if($('#television_video').length)
				swfobject.embedSWF('/news_multimedia.swf', 'television_video', '700', '407', '9.0.0', '/flash/expressInstall.swf');
			if($('#radio').length)
				swfobject.embedSWF('http://www.google.com/reader/ui/3247397568-audio-player.swf?audioUrl=/gallery/state_of_nevada.mp3', 'radio', '400', '27', '9.0.0', '/flash/expressInstall.swf');
			if($('#home_video').length)
				swfobject.embedSWF('/v1.swf', 'home_video', '984', '508', '9.0.0', '/flash/expressInstall.swf');
		}
	};
	
	
	var Validation = this.Validation = {
		dictionary: {
		
		},
		check: function($target) {
			return false;
		}
	}
	
	$(function(){
    $('.fadein img:gt(0)').hide();
    setInterval(function(){
      $('.fadein :first-child').fadeOut(1000)
         .next('img').fadeIn(1000)
         .end().appendTo('.fadein');}, 
      5000);
	});
	
	
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, '');
	};

	$(document).ready(function() {
		Event.bindNavEvents();
		Event.bindPopoverEvents();
		Event.bindPopupEvents();
		Event.bindFaqEvents();
		Event.bindNewsEvents();
		Event.bindFormEvents();
		Flash.place();
	});
})(jQuery);
