/* 
  Sign up form

	AutoclearField and SignUp track the state of each field by 
	setting its class to edited, error, or no class.  No class
	indicates the default state when nothing is entered.  The 
	color of the text field in each state is determined by the CSS. 
*/

var AutoclearField2 = {
	setup: function(field, defaultText) {
		var field = $(field);
		field.value = defaultText;
		field.defaultText = defaultText;  
		field.observe('focus', AutoclearField2.onFocus);
		field.observe('blur', AutoclearField2.onBlur);
	},
	
	onFocus: function(event) {
		var field = event.element();
		if (field.className != 'edited') {
			field.className = 'edited';
			field.clear(); 
		}
	}, 
	
	onBlur: function(event) {
		var field = event.element();
		if (!field.present()) {
			field.className = ''; 
			field.value = field.defaultText; 
		}	
	}
};

var whitepaper = {
	setup: function() {
        $('whitepaper').observe('submit', this.onSubmit);
		AutoclearField2.setup('first_name', 'First Name');
		AutoclearField2.setup('last_name', 'Last Name');
		AutoclearField2.setup('company', 'Company');
		AutoclearField2.setup('email', 'Email');
		AutoclearField2.setup('phone', 'Phone');
	}, 
	
	onSubmit: function(event) {
        if (!whitepaper.validate()) {
            event.stop(); 
        }
	}, 
	
	validate: function() {		
		if (whitepaper.isEmpty('first_name')) {
			window.alert("Please enter your first name");
			return false; 
		} 
		
		if (whitepaper.isEmpty('last_name')) {
			window.alert("Please enter your last name");
			return false; 
		}
		
		if (whitepaper.isEmpty('company')) {
			window.alert("Please enter company");
			return false; 
		}
		
		if (whitepaper.isEmpty('email')) {
			window.alert("Please enter your email");
			return false; 
		} else if (whitepaper.isInvalidEmail('email')) {
			window.alert("Please enter a valid email");
			return false; 
		}
		
		return true; 	
	}, 
	
	isEmpty: function(field) {
		field = $(field);
		return field.className != 'edited' || !field.present(); 
	}, 
	
	isInvalidEmail: function(field) {
		field = $(field);
		var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		return !filter.test(field.value);
	}
}

/*  -----------------------------------------------------------  */

var AutoclearField = {
	setup: function(field, defaultText) {
		field.value = defaultText;
		field.defaultText = defaultText;  
		field.observe('focus', AutoclearField.onFocus);
		field.observe('blur', AutoclearField.onBlur);
	},
	
	onFocus: function(event) {
		var field = event.element();
		if (!field.edited) {
			field.edited = true; 
			field.clear(); 
		}
	}, 
	
	onBlur: function(event) {
		var field = event.element();
		if (!field.present()) {
			field.edited = false; 
			field.value = field.defaultText; 
		}		
	}
};

var Resources = {
	unlock: function() {
		Cookie.set('resources_unlocked', 'true', 30, '/');
	}, 
	
	isUnlocked: function() {
		return Cookie.get('resources_unlocked') == 'true'; 
	}, 
	
	showUnlockNotice: function() {
		if (Cookie.get('show_unlock_notice')) {
			Cookie.remove('show_unlock_notice', '/');		
			$('notice').show(); 
		}
	}, 

	updateResourceLock: function(level) {
		if ($$('.lock_icon').length == 0 || $$('a.protected').length == 0) return; 
		
		if (Resources.isUnlocked()) {
			$$('.lock_icon').each(function(i) { i.hide(); }); 
			Resources.showUnlockNotice();
		} else {
			$$('a.protected').each(function(a) {
	     	a.href = General.pathPrefix(level)  + "unlock.php";
				a.onclick = Resources.setReturnURL; 				
			});
		}
	}, 
	
	setReturnURL: function() {
		Cookie.set('return_url', window.location, null, '/')
	}
};

var Newsletter = {
  SpamList: [ 'gmail.com', 'yahoo.com', 'hotmail.com' ], 
  
	validate: function(event) {
		var email = $$("#newsletter form")[0].email.value; 
		if (!email || email.match(/^\s*$/)) {
			alert("Please enter your email"); 
			event.stop(); 
		} else if (!Contact.checkemail(email)) {
			alert("Please enter a valid email");
			event.stop(); 
    } else if (Newsletter.isSpam(email)) {
      alert("Sorry, we do not accept sign ups from free email providers. Please use another email address.");
      event.stop();
    }
  }, 
	
  // Returns true if the email address is using a free service provider. 
	isSpam: function(email) {
    return this.SpamList.any(function(domain) { 
      return email.indexOf('@' + domain) != -1; 
    }); 
  }
}; 

var Contact = {	
	init: function() {
		var form = document.getElementById('contact_form');
		form.retURL.value = Cookie.get("return_url");		
	},
	
	/**
	 * Set isToUnlock to true if the contact form is sent to unlock a resource.  By default 
	 * it's set to false, which means the user simply clicked the Contact Us link on top 
	 * of the page. 
	 */
	validateForm: function(isToUnlock) {
		var form = document.getElementById("contact_form");
		
		var first_name = form.first_name.value;
		var last_name = form.last_name.value;
		var title = form.title.value;
		var company = form.company.value;
		var email = form.email.value;

		if (!first_name) {
			window.alert("Please enter your first name");
			return false;
    } else if(!last_name) {
      window.alert("Please enter your last name");
      return false;
		} else if(!company) {
			window.alert("Please enter your company / organization");
			return false;
		} else if(!email) {
			window.alert("Please enter your email address");
			return false;
		} else if (!Contact.checkemail(email))	{
		  window.alert("Please enter a valid email address");
			return false;
		} else {
			Resources.unlock();
			if (isToUnlock) Cookie.set('show_unlock_notice', 'true', null, '/');
		}
	}, 
		
	checkemail: function(str) {
		var testresults=true;
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		var emailPat=/^(.+)@(.+)$/; 
		var matchArray=str.match(emailPat); 
		if (matchArray==null) {	testresults=false; }
		if (!filter.test(str)) { testresults=false; }

		return testresults;
	}
};

var Cookie = {
	// expires is in days
	set: function(name, value, expires, path, domain, secure) {
		var today = new Date();
		if (expires) expires = expires * 1000 * 60 * 60 * 24;
		var expiresDate = new Date(today.getTime() + expires);

		document.cookie = name + "=" + encodeURIComponent(value) +
		( expires ? "; expires=" + expiresDate.toGMTString() : "" ) + 
		( path    ? "; path=" + path : "" ) + 
		( domain  ? "; domain=" + domain : "" ) +
		( secure  ? "; secure" : "" );
	}, 
	
	remove: function(name, path, domain) {
		document.cookie = name + "=" +
		( path   ? "; path=" + path : "" ) +
		( domain ? "; domain=" + domain : "" ) +
		"; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	},
	
	// Returns value of named cookie.  Returns null if cookie can't be found. 
	get: function(name) {
	    var allcookies = document.cookie;

	    if (allcookies == "") return null;

	    var cookies = allcookies.split('; ');
	    var cookie = null;
	    for(var i = 0; i < cookies.length; i++) {
	        if (cookies[i].substring(0, name.length+1) == (name + "=")) {
	            cookie = cookies[i];
	            break;
	        }
	    }
	
	    if (cookie == null) return null;
		
		return decodeURIComponent(cookie.substring(name.length+1));
	}

}


$(document).ready(function(){
   $("#commentform input#submit").hover(function() {
       $(".success").fadeIn();
   });
});


