// Global Functions
function wordToUpper(strSentence) {
	return strSentence.toLowerCase().replace(/\b[a-z]/g, convertToUpper);
	function convertToUpper() {
		return arguments[0].toUpperCase();
	}
}

//	jQuery Slug Generation Plugin by Perry Trinier (perrytrinier@gmail.com)
// Licensed under the GPL: http://www.gnu.org/copyleft/gpl.html
jQuery.fn.slug = function(options) {
	var settings = {
		slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready() 
		hide: true	 // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span. 
	};
	if(options) {
		jQuery.extend(settings, options);
	}
	$this = jQuery(this);
	jQuery(document).ready( function() {
		if (settings.hide) {
			jQuery('input.' + settings.slug).after("<span class="+settings.slug+"></span>");
			jQuery('input.' + settings.slug).hide();
		}
	});
	makeSlug = function() {
			var slugcontent = $this.val();
			var slugcontent_hyphens = slugcontent.replace(/\s/g,'-');
			var finishedslug = slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,'');
			jQuery('input.' + settings.slug).val(finishedslug.toLowerCase());
			jQuery('span.' + settings.slug).text(finishedslug.toLowerCase());

		}
	jQuery(this).keyup(makeSlug);
	return $this;
};

// URL Encoder & Decoder (http://plugins.jquery.com/project/URLEncode)
$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
	while(x<c.length){var m=r.exec(c.substr(x));
	if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
	}else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
	o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
	URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
	while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
	t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});
 
// Document Load
$(document).ready(function(){

	// Rotating slider
	if ( $('#slider').length > 0 ){
		$('.slide-item').hide().first().show();
		var sliderInterval = 0;
		function triggerNextSlide(){
			if($('#slider-nav ul li a.active').parent().is(':last-child')){
				$('#slider-nav ul li:first-child a').trigger('click');
			} else {
				$('#slider-nav ul li a.active').parent().next().find('a').trigger('click');
			}
		}
		sliderInterval = setInterval ( triggerNextSlide, 8000 );
		$('#slider-nav span').click(triggerNextSlide);
		$('#slider-nav ul li a').click(function(){
			$(this).addClass('active').parent().siblings().find('a').removeClass('active');
			var targetSlide = $(this).attr('href');
			$('.slide-item:not('+targetSlide+')').hide();
			$(targetSlide).fadeIn();
			clearInterval(sliderInterval);
			sliderInterval = setInterval ( triggerNextSlide, 8000 );
			return false;
		});
	}
	
	// Use Geo IP to get the current users country
	var countryCode;
	if(jQuery.url.param('country')){
		countryCode = jQuery.url.param('country');
	}
	else {
    	countryCode = geoip_country_code();
	}
	
	
	// If their in the UK
	if(countryCode == 'UK' || countryCode == 'AU' ) {	
		var wordList = {};
		var replacedText = null;	
		
		$.ajax({
		    type: 'GET',
		    url: '/js/json/translations.json',
		    dataType: 'json',
		    success: function(json) {
				$.each(json.translations.word, function(i,word){								
					wordList[word.us] = word.uk; 
				});			    
		    },
		    data: {},
		    async: false
		});			
				
		var reverser = new Translator(function( text ) {					
			replacedText = text;											
			$.each(wordList, function(index, value){				
				//var theRegex = new RegExp("\\b"+index+"\\b","ig");								
				var theRegex = new RegExp("\\b("+index+")(?=\\b|s|ed|d|ing|ly)","ig");								
				
				//replacedText = replacedText.replace(theRegex, value);				
				
				replacedText = replacedText.replace(theRegex, function (s, pat) {
					var firstLetter = s.substring(0,1);
					if(firstLetter == firstLetter.toUpperCase()) {
						return value.substr(0,1).toUpperCase() + value.substr(1,value.length);
					}
					else {
						return value;
					}
				});
			});							
			return replacedText;			
		});		
		reverser.traverse(document.body);
	}
	
	// Windows Specific CSS
	if (navigator.appVersion.indexOf("Win")!=-1) {
		$('body').addClass('os-windows');
	}
	// Load Live Search Plug-in
	$('#terms').liveSearch({ajaxURL: '/ajax-results.php?terms='});
	// Events Calendar
	if ($('.calendar').length > 0) {
		$.getScript('js/calendar.js');
	}
	// Expand
	if ($('body').attr('id').indexOf('investors') > -1) {
		$.getScript('js/team.js');
	}
	// Sub Navigation
	$('ol#sub_nav li:last').addClass('last');
	
	// Open externa links in new window	with a popup warning except for a few exceptions
    $('a[href^=http://]').each(function(){
        var theHREF = $(this).attr('href').toLowerCase();    
        if( theHREF.indexOf('enernoc.com') < 0 && 
                theHREF.indexOf('youtube.com') < 0 && 
                theHREF.indexOf('brainshark.com') < 0 &&
                theHREF.indexOf('energysmartconference2011.com') < 0 &&
                theHREF.indexOf('gepllc.com') < 0) {
                
            $(this).attr('target','_blank').addClass('external');
        }
    });	
	
	// External link message exceptions
	$('ol#main_nav a[href^=http://], a[href^=http://www.clicktools.com], li.button a[href^=http://], a.internal').removeAttr('target').removeClass('external');
	$('a.internal').attr('target','_blank');
	$('#external-message').hide();
	$('a.external').click(function(){
		var $href = $(this).attr('href');
		$.blockUI({  
			message: $('#external-message'),  
			css: { width: '430px' }
		});
		$('#external-continue').attr('href',$href);
		$('#external-continue').click(function(){
			$.unblockUI();
			return true;
		});
		return false;
	});
	// Groups
	if ($('#group').length > 0) {
		$.getScript('js/group.js');
	}
	// Adwords Content
	if ($('#adwords-content').length > 0) {
		$('#adwords-content p:last').addClass('last');
	}
	// Callout effects
	$('div.callout ul.list').each(function(){
		 $('li:last',this).addClass('last');
	});
	// Quicksearch Plugin
	if ($('.quicksearch').length > 0) {
		$.getScript('js/jquery.quicksearch.js',function(){
			$('.quicksearch li').quicksearch({
				position: 'before',
				attached: '#quicksearch-input',
				loaderImg: 'img/ajax-loader.gif',
				labelText: '&nbsp;',
				focusOnLoad: false
			});
		});
	}
	// Supporting Content -- Rounded Corners
	if ($('#supporting-content li.image').length > 0){
		$('#supporting-content li.image').each(function(){
			$(this).append('<span class="corner tl"></span>').append('<span class="corner tr"></span>').append('<span class="corner bl"></span>').append('<span class="corner br"></span>');
		});
	}
	// Table Sorter
	if ($('table.sortable').length > 0) {
		$.getScript('js/jquery.tablesorter.js',function(){ 
			$('table.sortable').tablesorter({
				sortList: [[0,0]]
			});
		});
	}
	// Focus & Blur
	if ($('input.valueFx').length > 0) {
		$.getScript('/js/jquery.valueFx.js',function(){ 
			$('input.valueFx').valueFx();
		});
	}
	// Read More (expand/collapse)
	if ($('a.continue').length > 0){
		// Current Nav States
		$.getScript('/js/jquery.url.packed.js',function(){
			var $anchor = jQuery.url.attr("anchor");
			$('a.continue').parent().next('div').hide();
			$('a.continue').click(function(){
				if ($(this).hasClass('stay') == false) {
					$(this).hide();
				}
				$(this).parent().next('div').slideToggle('fast');
				return false;
			});
			if($anchor) {
				$('#'+$anchor).parent().find('a.continue').hide().parent().next('div').css({'display':'block'});
			}
		});
	}
	// Anti-aliased Rounded Edges
	if ($('div.rounded-container').length > 0) {
		$.getScript('/js/jquery.curvycorners.packed.js',function(){ 
			$('.rounded-container').corner({
				tl: { radius: 11 },
				tr: { radius: 11 },
				bl: { radius: 11 },
				br: { radius: 11 },
				antiAlias: true
			}).css({'visibility':'visible'});
			$('.rounded-container').each(function(index){
				if($(this).hasClass('right')){
					$(this).parent().addClass('right');
				}
				if($(this).hasClass('left')){
					$(this).parent().addClass('left');
				}
			});
		});
	}
	// Safe Mailto's
	if ($('a.email').length > 0){
		$.getScript('/js/jquery.mailto.js',function(){ 
			$('.email').mailto();
		});
	}
	// Press Releases
	if ($('ul.articles').length > 0){
		$.getScript('js/articles.js');
	}
	// Form Plugin
	if ($('div.comment-form form').length > 0) {
		$.getScript('js/jquery.livequery.pack.js');
		$.getScript('js/jquery.form.js');
		$.getScript('js/jquery.metadata.js');
		$.getScript('js/jquery.validate.js', function(){
			$.getScript('js/forms.js');
		});
	}
	// Google Analytics Download Tracking
	if ( $('a[href$=.pdf]').length > 0 ) {
		$.getScript('/js/jquery.url.packed.js',function(){
			$('a[href$=.pdf]').click(function(){
/*
				var pdfName = $(this).attr('href');
				var currentPage = jQuery.url.attr("path");
				var pageview = '/pdf/' + pdfName + '/';
				pageTracker._trackPageview(pageview);
				if(window.console&&window.console.log) { console.log('GA pageview tracked: '+pageview); }
*/
				return true;
			});
		});
	}
	if ( $('div[id*=audioplayer_]').length > 0 ) {
		//$.getScript('/js/jquery.url.packed.js',function(){
			$('object[id*=audioplayer_]').live('click',function(){
				var fileName = $(this).parent().attr('rel');			
				//Track event
				_gaq.push(['_trackEvent', 'Podcast', 'Play', fileName]);
/*
				var flashvars = $(this).find('param[name="flashvars"]').val();
				var fileName = $(this).parent().attr('rel');
				if(window.console&&window.console.log) { console.log('fileName: '+fileName); }
				var currentPage = jQuery.url.attr("path");
				var pageview = '/podcast/' + fileName + '/';
				pageTracker._trackPageview(pageview);
				if(window.console&&window.console.log) { console.log('GA pageview tracked: '+pageview); }
*/
				return true;
			});
		//});
	}
	if ( $('a[rel*="shadowbox"]').length > 0 ) {
		$.getScript('/js/jquery.url.packed.js',function(){
			$('a[rel*="shadowbox"]').click(function(){
/*
				var linkUrl = $(this).attr('href');
				var currentPage = jQuery.url.attr("path");
				var pageview = '/modal/'+linkUrl+'/';
				pageTracker._trackPageview(pageview);
				if(window.console&&window.console.log) { console.log('GA pageview tracked: '+pageview); }
*/
				return true;
			});
		});
	}
	// Automatic Link Icons
	$('a').each(function(){
		if (this.href.indexOf('.pdf') != -1) {
			//This is sadly a one off fix for a single document in the UK Opportunities section
			if ($(this).attr('href') != '/htmlmail/documents/EnerNOC_Demand_Response_Article_Energy_World_October_2010.pdf' && !$(this).hasClass('no-icon')) {
				$(this).attr('target', '_blank');
				$(this).addClass('pdf');		
			}
		}
		if (this.href.indexOf('.doc') != -1) {
			$(this).attr('target', '_blank');
			$(this).addClass('doc');
		}
		if (this.href.indexOf('.xls') != -1) {
			$(this).attr('target', '_blank');
			$(this).addClass('xls');
		}
		if (this.href.indexOf('.zip') != -1) {
			$(this).attr('target', '_blank');
			$(this).addClass('zip');
		}
		if (this.href.indexOf('.ppt') != -1) {
			$(this).attr('target', '_blank');
			$(this).addClass('ppt');
		}
	});
	// Countries Field
	if ($('#country').length > 0) {
		// Options on demand
		var regionClone = $('#region').html();
		$('#country').change(function(){
			$('#region').html(regionClone);
			if ($('option:selected', this).hasClass('region-toggler')) {
				var country = $(this).val();
				var countryClass = country.toString();
				countryClass = countryClass.toLowerCase();
				countryClass = countryClass.replace(/ /gi, "-");
				$('#region option:not(.'+countryClass+', #region-label)').remove();
				$('#region').val('Select your state or province&hellip;');
			} else {
				$('#region option:not(#region-none)').remove();
				$('#region').val('Not Applicable');
			}
		});
	}
	// Contact Form
	if ( ($('#about-contact').length > 0) || ($('#enroll-questionnaire').length > 0) ) {
		$('input:hidden').addClass('hide');
		$('input:radio').addClass('radio');
		$('input:checkbox').addClass('checkbox');
		$('input:text').addClass('text');
		
		$('#success-msg').hide();
		if ($('#about-contact').length > 0) {
			var $form = $('#contact-form');
		} else {
			var $form = $('#enroll-questionnaire');
		}
	}
	// Required Fields
	if ($('li.required').length > 0) {
		$('li.required label').each(function(){
			var $required = ' <span class="red">*</span>';
			$(this).append($required);
		});
	}
	/* Login
	$('#ut-sign-in a').click(function(){
		$.blockUI({  
			message: $('#login-buttons'),  
			css: { 
				width: '26%',
				left: '37%',
				top: '158px'
			}  
	  });
		return false;
	});
	*/
	// Download Form & Block UI
	if ($('.download').length > 0) {
		if ($.cookie('downloadAccess')) { } else {
			$('.download').click(function() {
				$('html body .blockUI *').css({
					'cursor':'default'
				});
				var $file = $(this).attr('href');
				$.blockUI({ message: $('#download-form') });
				$('#download-form #submit').click(function(){
					// Form Elements
					var $name = $('#download-form #name');
					var $businessName = $('#download-form #business-name');
					var $email = $('#download-form #email');
					var $alertBox = $('#download-form .alert');
					// Regex and other
					var $hasError = false;
					var $emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
					// Alert box
					$alertBox.empty();
					// Validation
					if ($name.val() == '') {
						$alertBox.append('<span class="error">You forgot to enter your <strong>name</strong>.</span>');
						$hasError = true;
					}
					if ($businessName.val() == '') {
						$alertBox.append('<span class="error">You forgot to enter your <strong>business name</strong>.</span>');
						$hasError = true;
					}
					if($email.val() == '') {
						$alertBox.append('<span class="error">You forgot to enter your <strong>email address</strong>.</span>');
						$hasError = true;
					} else if(!$emailReg.test($email.val())) {
						$alertBox.append('<span class="error">Please enter a <strong>valid email address</strong>.</span>');
						$hasError = true;
					}
					if($hasError == false) {
						$alertBox.empty().html('<span class="success"><strong>Thank you!</strong> The download location for this file has been sent to <strong>' + $email.val() + '</strong></span>');
						$('html body .blockUI *').css({'cursor':'wait'});
						setTimeout(function() { 
							jQuery.unblockUI({ 
								onUnblock: function() { 
								$.post('post.php', { file: $file, email: $email.val(), name: $name.val(), businessName: $businessName.val() });
									$('html body .blockUI *').css({
										'cursor':'auto'
									});
									$.cookie('downloadAccess', 'yes', {expires: 365}); 
								} 
							}); 
						}, 3000);
					}
				});
				$('#download-form #cancel').click(function(){
					$.unblockUI();
				});
				return false;
			});
		}
	}
	// Download Form & Block UI
	if ($('.video').length > 0) {
		if ($.cookie('videoAccess')) { } else {
			var $video = $('.video').attr('href');
			$($video).hide();
			$('.video').click(function() {
				$videoPlay = $(this);
				$videoTitle = $(this).attr('title');
				$('html body .blockUI *').css({
					'cursor':'default'
				});
				var $video = $(this).attr('href');
				$.blockUI({ message: $('#video-form') });
				$('#video-form input').show();
				$('#video-form #submit').click(function(){
					// Form Elements
					var $name = $('#video-form #name');
					var $businessName = $('#video-form #business-name');
					var $email = $('#video-form #email');
					var $alertBox = $('#video-form .alert');
					// Regex and other
					var $hasError = false;
					var $emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
					// Alert box
					$alertBox.empty();
					// Validation
					if ($name.val() == '') {
						$alertBox.append('<span class="error">You forgot to enter your <strong>name</strong>.</span>');
						$hasError = true;
					}
					if ($businessName.val() == '') {
						$alertBox.append('<span class="error">You forgot to enter your <strong>business name</strong>.</span>');
						$hasError = true;
					}
					if($email.val() == '') {
						$alertBox.append('<span class="error">You forgot to enter your <strong>email address</strong>.</span>');
						$hasError = true;
					} else if(!$emailReg.test($email.val())) {
						$alertBox.append('<span class="error">Please enter a <strong>valid email address</strong>.</span>');
						$hasError = true;
					}
					if($hasError == false) {
						$(this).attr("disabled", true);
						$alertBox.empty().html('<span class="success"><strong>Thank you!</strong></span>');
						$('html body .blockUI *').css({'cursor':'wait'});
						setTimeout(function() { 
							jQuery.unblockUI({ 
								onUnblock: function() { 
								$.post('video.php', { video: $videoTitle, email: $email.val(), name: $name.val(), businessName: $businessName.val() });
									$('html body .blockUI *').css({
										'cursor':'auto'
									});
									$($video).show();
									//$.cookie('videoAccess', 'yes', {expires: 365}); 
									$($videoPlay).hide();
								}
							}); 
						}, 3000);
					}
				});
				$('#video-form #cancel').click(function(){
					$.unblockUI();
				});
				return false;
			});
		}
	}
	
	// Custom Thickbox Displays
	if ( $('a.customTB').length > 0 ){
		$.getScript('/js/jquery.thickbox.js',function(){
			// Get urls params (requires jQuery URL parser plugin)
			var modal = jQuery.url.param('modal');
			var currentPath = jQuery.url.attr('path');
			// Load via url params
			if( modal ) {
				var link = $('a.customTB:eq('+modal+')').attr('href');
				if( $('a.customTB:eq('+modal+')[href*="/case-studies/"]').length > 0 ) {
					// It's a case study modal
					link += '?keepThis=true&TB_iframe=true&height=500&width=725';
				} else {
					// It's a video modal
					link += '?keepThis=true&TB_iframe=true&height=350&width=725';
				}
				
				$('a.customTB:eq('+modal+')').attr('href',link).trigger('click');
			}
			$('a.customTB').die().click(function(){
				// Load modal
/*
				var eqIndex = $('a.customTB').index( $(this) );
				window.location = currentPath + '?modal='+eqIndex;
*/
				return false;
			});
			$('.TB_overlayMacFFBGHack').css({
				backgroundImage : 'url(../img/macFFBgHack.png)'
			});
			$('.TB_overlayBG').css({
				backgroundColor : '#000',
				filter : 'alpha(opacity=75)',
				'-moz-opacity' : '0.75',
				opacity : '0.75'
			});
		});
	} 
	
	// Newsletter
	if ($('#press-enernoc-newsletter').length > 0){
		$.localScroll.hash({
			queue:true
		});
		$.localScroll();
	}
	if ($('ul.quicklinks').length > 0){
		$('a.continue').trigger('click');
	}
	
	
	//SF Thank you messages
	if( $('#enroll-questionnaire').length > 0 ) {
		if( jQuery.url.param('ty') ) {
		
			switch( jQuery.url.param('ty') ) {
				case 'ty': 
					_gaq.push(['_trackPageview', "/thank-you.php"]); 
					//pageTracker._trackPageview('/thank-you.php');
					//if(window.console && window.console.log) { console.log('GA pageview tracked /thank-you.php'); }
					break;
								
				case 'tys': 
					//pageTracker._trackPageview('/thank-you-sidebar.php');
					_gaq.push(['_trackPageview', "/thank-you-sidebar.php"]); 
					//if(window.console && window.console.log) { console.log('GA pageview tracked /thank-you-sidebar.php'); }
					break;			
					
				case 'tyc': 
					_gaq.push(['_trackPageview', "/thank-you-campaign.php"]); 
					//pageTracker._trackPageview('/thank-you-campaign.php');
					//if(window.console && window.console.log) { console.log('GA pageview tracked /thank-you-campaign.php'); }
					break;			
			
			}
		}
	}
	
});

// Validation
function validateForm(theForm) {
	var error = "";
	if ($('#first_name').length > 0){ var first_name	= theForm.first_name.value; }
	if ($('#last_name').length > 0){ var last_name 	= theForm.last_name.value; }
	if ($('#email').length > 0){ var email 		= theForm.email.value; }
	if ($('#company').length > 0){ var company 	= theForm.company.value; }
	if ($('#city').length > 0){ var city 		= theForm.city.value; }	
	if ($('#region').length > 0 || $('#state').length > 0){ var state 		= theForm.state.value; }
	if ($('#phone').length > 0){ var phone 		= theForm.phone.value; }
	if ($('#demand_response').length > 0){ var response	= theForm.demand_response.value; }
	if ($('#energy_efficiency').length > 0){ var efficiency	= theForm.energy_efficiency.value; }
	if ($('#energy_procurement').length > 0){ var procurement	= theForm.energy_procurement.value; }
	if ($('#carbon_management').length > 0){ var carbon 		= theForm.carbon_management.value; }
	
	// If it's NOT the Mini Form
	if(typeof(theForm.street) != "undefined"){
		var address_1	= theForm.street.value;
		var address_2	= theForm.street_2.value;
		var hear			= theForm.hear.value;
		var comments	= theForm.comments.value;
	}
	
	if(typeof(theForm.signup) != "undefined"){
		if(theForm.signup.checked) {
			$('#00N30000003XYCt').val("Web form");			
			if ($('#emailOptOut').length > 0) {			
				$('#emailOptOut').val("");
			}
		}
		else {
			$('#00N30000003XYCt').val("Declined");
			if ($('#emailOptOut').length > 0) {			
				$('#emailOptOut').val("1");
			}						
		}
	}	

	if(first_name == "") 	{ error += '<li class="red">Enter your first name.</li>';}
	if(last_name == "") 		{ error += '<li class="red">Enter your last name.</li>';}
	if(email == "") 			{ error += '<li class="red">Enter your email.</li>';}
	if(company == "") 		{ error += '<li class="red">Enter your company.</li>';}
	if(city == "") 			{ error += '<li class="red">Enter your city.</li>';}
	
	if ($('#country').length > 0) { 
		var country 	= theForm.country.value; 
		if(country == "") 		{ 
			error += '<li class="red">Select your country.</li>';
		}		
		else {		
			if ($('#region').length > 0) { 				
				var state 	= theForm.state.value; 
				switch(country) {
					case "US":
					case "Argentina":
					case "Australia":
					case "Austria":
					case "Belgium": 
					case "Brazil": 
					case "Canada": 
					case "Ecuador": 
					case "Japan": 
					case "Mexico": 
					case "Peru": 
					case "United Kingdom":	
						if(state == "") {
							error += '<li class="red">Select your state or province.</li>';			
						}	
					break;
				}				
			}	
		}
	}	
	
	if ($('#state').length > 0) { 		
		var state 	= theForm.state.value; 
		if(state == "") 		{ 
			error += '<li class="red">Select your state</li>';
		}			
	}	
	
	if(phone == "") 			{ error += '<li class="red">Enter your phone number.</li>';}	
	
	if(error == "")	{
		
		if((address_2 != "") && (typeof(address_2) != "undefined")) {theForm.street.value+= ", " + address_2;}
		
		var interests = "";
		var interests_arr = [];
		if(theForm.demand_response.checked) {
			interests+= theForm.demand_response.value;
			interests_arr.push('<option value="'+ theForm.demand_response.value +'" selected="selected">'+ theForm.demand_response.value +'</option>');
		}
		
		if(theForm.energy_efficiency.checked) {
			if(interests != "") {interests+= ", ";}
			interests+= theForm.energy_efficiency.value;
			interests_arr.push('<option value="'+ theForm.energy_efficiency.value +'" selected="selected">'+ theForm.energy_efficiency.value +'</option>');
		}
		
		if(theForm.energy_procurement.checked) {
			if(interests != "") {interests+= ", ";}
			interests+= theForm.energy_procurement.value;
			interests_arr.push('<option value="'+ theForm.energy_procurement.value +'" selected="selected">'+ theForm.energy_procurement.value +'</option>');
		}	
		
		if(theForm.carbon_management.checked) {
			if(interests != "") {interests+= ", ";}
			interests+= theForm.carbon_management.value;
			interests_arr.push('<option value="'+ theForm.carbon_management.value +'" selected="selected">'+ theForm.carbon_management.value +'</option>');
		}		
		
		theForm.description.value = "";
			
		if(typeof(theForm.q_3) != "undefined" && theForm.q_3.value != "") {
			theForm.description.value+= "Electricity Provider: " + theForm.q_3.value;
		}
		
		if(interests != "") {
			if ($('#00N30000005XWAf').length > 0) {
				$('#00N30000005XWAf').html(interests_arr.join(''));
			}
		}	
		
		if(typeof(hear) != "undefined" && hear != "") {
			if(theForm.description.value != "") {theForm.description.value+= " | ";}
			theForm.description.value+= "Hear About: " + hear;		
		}			
		
		if(typeof(comments) != "undefined" && comments != "") {
			if(theForm.description.value != "") {theForm.description.value+= " \n";}
			theForm.description.value+= "Comments: " + comments;
		}
		return true;
	}
	else {
		$('html').animate({scrollTop:0}, 'slow',function(){
			if ($('#errors').length > 0) {
				$('#errors').remove();
			}
			$('#enroll-questionnaire').before('<div id="errors"><strong>Please correct the following issues and try again:</strong><ol class="validation">'+error+'</ol></div>');
			if($('body').hasClass('landing')){
				$('ol.validation').slideDown();
			} else {
				$('ol.validation').fadeIn();
			}
		}); 
		return false;
	}
}

function validateMiniForm(theForm) {
	var error = "";
	var first_name	= theForm.first_name.value;
	var last_name 	= theForm.last_name.value;
	var company 	= theForm.company.value;
	var email   	= theForm.email.value;
	var phone   	= theForm.phone.value;

	if(first_name == "") {error += '<li class="red">Enter your first name.</li>';}
	if(last_name == "") {error += '<li class="red">Enter your last name.</li>';}
	if(company == "") {error += '<li class="red">Enter your company.</li>';}
	if(email == "") {error += '<li class="red">Enter your email.</li>';}
	if(phone == "") {error += '<li class="red">Enter your phone.</li>';}
	
	if(error == "")	{
		return true;
	}
	else {
		$('html').animate({scrollTop:0}, 'slow',function(){
			if ($('#errors').length > 0) {
				$('#errors').remove();
			}
			$('#enroll-questionnaire').before('<div id="errors"><strong>Please correct the following issues and try again:</strong><ol class="validation">'+error+'</ol></div>');
			if($('body').hasClass('landing')){
				$('ol.validation').slideDown();
			} else {
				$('ol.validation').fadeIn();
			}
		}); 
		return false;
	}
}
