
Event.observe(window,'load',function(){
	$('email-button').onclick = insertForm;
	$('email-div').setStyle({ clear: 'both', display: 'none' });
});

function email(){
	
    validEmail = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/gi;
	if(!$("emailpage").toEmail.value.match(validEmail)){
		Effect.Shake("toEmail");
		$("emailpage").toEmail.style.background = "yellow";
		return false;
	}

	if(!$("emailpage").fromEmail.value.match(validEmail)){
		Effect.Shake("fromEmail");
		$("emailpage").fromEmail.style.background = "yellow";
		return false;
	}

	$("emailpage").url_address.value = location.href;

	new Ajax.Request("/includes/emailer/articles/_emailer.cfm", {
		method: "post",
		parameters: Form.serialize("emailpage")+"&ajax=1",
		onSuccess: function(xhr) {
			Element.update("email-div",xhr.responseText);
    	},
		onFailure: function(){
			//alert("Technical problems please try reloading page");
			alert("Technical problems, please try to reload page. function email().");
		}
	});

	return false;
}

function insertForm(){ 

	if(this.id != "email"){ 
		this.id = "email"; 
	} else { 
		this.id = ""; 
	} 
	article_type = "article";
	article_title = encodeURI($("frameBelowHeader").getElementsByTagName("h1")[0].innerHTML);
	article_title = cleanString(article_title);
	hack = this.id; 

	new Ajax.Request("/includes/emailer/articles/_email_ajax.cfm", { 
		method: "post",
		parameters: "emailtype="+article_type+"&title="+article_title,
		onSuccess: function(xhr) { 
			if(hack == "email"){ 
				Element.update("email-div", xhr.responseText); 
			} 
			Effect.toggle('email-div', 'slide'); 
		}, 
		onFailure: function(){ 
			window.location = location.href+"/email"; 
		} 
	});

	return false; 
}

function cleanString(str){
	var result = str;
	var pattern = /\?$/; 	
	if(pattern.test(str)){
		max = str.length - 1;
		result = str.substring(0,max);
	}
	return result;
}

