Event.onReady(email_form_hook);

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(t) {
			Element.update("toolBox",t.responseText);
    	},
		onFailure: function(){
			//alert("Tecnical problems please try reloading page");
		}
	});

	return false;
}


function gettype(){
	var type = "";
	var emailtype = "";
	var path_info = location.href;
	var urlpattern = /http:\/\/.*?\/(.*?)\/.*[\/]?/;
	if(urlpattern.test(path_info)){
		type = RegExp.$1;
	} else {
		type = "general";
	}
	switch(type){
		case "recipes":
			emailtype = "Amex_Recipe";
		break;
		case "articles":
			emailtype = "Amex_SimpleArticle";
		break;
		default: emailtype = "generic";
	}
	return emailtype;	
}

function insertform(){
	
	if(this.id != "email"){
		this.id = "email";
	} else {
	    this.id = "";
	}
	article_type = gettype();
	article_title = encodeURI($("frameBelowHeader").getElementsByTagName("h1")[0].innerHTML);
	hack = this.id;

	article_title = cleanString(article_title);
	
	new Ajax.Request("/includes/emailer/articles/_email.cfm", {
		method: "post",
		parameters: "emailtype="+article_type+"&title="+article_title,
		onSuccess: function(t) {
			if(hack == "email"){
			  Element.update("toolBox", t.responseText);
			}
			Effect.toggle('toolBox', '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;
}

function email_form_hook(){
	if($("emailpage")){
	  $("emailpage").onsubmit = email;
	}
	$$("a.email_button")[0].onclick = insertform;
}


