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

	// Use Geo IP to get the current users country
	var countryCode;
	if(jQuery.url.param('country')){
		countryCode = jQuery.url.param('country');
	}
	
	/* If their in the UK */
	if(countryCode == 'UK') {	
		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 links in new window
	$('a[href^=http://]').attr('target','_blank').addClass('external');
	$('a[href^=http://www.enernoc.com], a[href^=http://www.youtube.com]').removeClass('external').removeAttr('target','_blank');
	$('ol#main_nav a[href^=http://], a[href^=http://investor.enernoc.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');
		});
	}
	// Automatic Link Icons
	$('a').each(function(){
		if (this.href.indexOf('.pdf') != -1) {
			$(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) {
	// Hide items for accessibility
		$('.countries-label, #region-none, #region option[class]').hide();
		// Change events
		$('#country').change(function(){
			if ($('option:selected', this).hasClass('region-toggler')) {
				if($('#region').is(':hidden')){
					$('#region, label[for="state"]').fadeIn();
				}
				var country = $(this).val();
				countryClass = country.toLowerCase().replace(" ", "-");
				$('#region option[class], #region-none').hide();
				$('#region option.'+countryClass+', #region-label').show();
				$('#region').val('Select your state or province&hellip;');
			} else {
				$('#region option[class], #region-label').hide();
				$('#region-none').show();
				$('#region, label[for="state"]').fadeOut();
				$('#region').val('');
			}
		});
	}
	// 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;
			});
		}
	}
	// Newsletter
	if ($('#press-enernoc-newsletter').length > 0){
		$.localScroll.hash({
			queue:true
		});
		$.localScroll();
	}
	if ($('ul.quicklinks').length > 0){
		$('a.continue').trigger('click');
	}
});

// Validation
function validateForm(theForm) {
	var error = "";
	var first_name	= theForm.first_name.value;
	var last_name 	= theForm.last_name.value;
	var email 		= theForm.email.value;
	var company 	= theForm.company.value;
	var city 		= theForm.city.value;
	var country 	= theForm.country.value;
	var state 		= theForm.state.value;
	var phone 		= theForm.phone.value;
	var response	= theForm.demand_response.value;
	var efficiency	= theForm.energy_efficiency.value;
	var procurement	= theForm.energy_procurement.value;
	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 == "") {error += '<li class="red">Select your country.</li>';}
	if($('#region').is(':not(:hidden)') && state == "") {error += '<li class="red">Select your state or province.</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 = "";
		if(theForm.demand_response.checked) {
			interests+= theForm.demand_response.value;
		}
		
		if(theForm.energy_efficiency.checked) {
			if(interests != "") {interests+= ", ";}
			interests+= theForm.energy_efficiency.value;
		}
		
		if(theForm.energy_procurement.checked) {
			if(interests != "") {interests+= ", ";}
			interests+= theForm.energy_procurement.value;
		}	
		
		if(theForm.carbon_management.checked) {
			if(interests != "") {interests+= ", ";}
			interests+= theForm.carbon_management.value;
		}		
		
		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(theForm.description.value != "") {theForm.description.value+= " | ";}
			theForm.description.value+= "Service Interest: " + interests;
		}	
		
		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;

	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(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;
	}
}