//<![CDATA[

var contactForm_config = 
{
	container : "#contact"	
}
var friendForm_config = 
{
	container : "#contact",
	form : "#friend_share"
}

$(function(){ 
/* This script fetches and process the contact form for blog entries */
	if($("a[rel*='cta']").length) { $("a[rel*='cta']").click(function(e){
		var url = getUrlVars($(this).attr("href"));
		var contact = "";
		if (url.length == 1 && url[0].substring(0,7) == "mailto:") {
			contact = $(this).attr("href").replace("mailto:","");		
		} else {
			if (url['contact']) contact = url['contact'];
			else contact = url['author'];
		}
		var success = false;
		var self  = $(this);
		$.ajax({
		   type: "POST",
		   url: "/scripts/ajax/contact_form.php",
		   data: "contact="+contact+"&mode="+url['mode'],
		   async: false,
		   success: function(msg){
				if (msg!="") {
				$(msg).appendTo('body');
				if (!$("#q_title").length) {
					$(contactForm_config.container+" h2").append("<span id='q_title'></span>");
				}
				if (url['title'] == undefined)  $("#q_title").empty().append($("h1").text());
				else $("#q_title").empty().append(url['title']);
				if (!$("input[name='bid']").length) {
					$(contactForm_config.container + " form").append("<input type='hidden' name='bid' value='"+url['bid']+"' />")
										.append("<input type='hidden' name='eid' value='"+url['eid']+"' />");
				}
				$(contactForm_config.container)
					.append($('<p class="close"><span class="simplemodal-close">Close</span></p>'))
					.modal({close: false, onClose: closeModal, onOpen: openModal, persist: false, onShow: onshowContact, position: [1,]});
				success = true;
				} 
		   },
		   error: function(obj,text,error) {   }
		 });
		return !success;
	});	}
/* This script fetches and process the email a friend form */
	if($("a.email_a_friend").length) {
		$("a.email_a_friend").click(function(e){
			var url = getUrlVars($(this).attr("href"));
			
			var success = false;
			var self  = $(this);
			$.ajax({
			   type: "POST",
			   url: "/scripts/ajax/email_a_friend_form.php",
			   data: "t="+url['t']+"&u="+url['u'],
			   async: false,
			   success: function(msg){
					if (msg!="") {
					$(msg).appendTo('body');
					$(friendForm_config.container+" form").append("<input type='hidden' name='t' value='"+url['t']+"' />")
											.append("<input type='hidden' name='u' value='"+url['u']+"' />");
					$(friendForm_config.container)
					.append($('<p class="close"><span class="simplemodal-close">Close</span></p>'))
					.modal({close: false, onClose: closeModal, onOpen: openModal, persist: false, onShow: onshowFriend, position: [1,]});
					success = true;
					} 
			   },
			   error: function(obj,text,error) {  }
			 });
			return !success;
		});
	}
/* This script link tracks */
	if($("a.track").length) {
		$("a.track").click(function(e){
			var href=$(this).attr("href");
			$.ajax({
			   type: "POST",
			   url: "/scripts/ajax/click_process.php",
			   data: "href="+href,
			   async: true
				   });
			return true;
		});
	}
});


function closeModal (dialog) {	dialog.data.fadeOut('slow', function () {dialog.container.fadeOut('slow', function () {dialog.overlay.slideUp('slow', function () {$.modal.close();$('.close').remove();$(contactForm_config.container).remove();});});	});}
function openModal (dialog) {	dialog.overlay.fadeIn('slow', function () {dialog.container.fadeIn('slow', function () {dialog.data.hide().slideDown('slow');});	});}


/*****************************************
 Take Care of Processing the Contact Form
*****************************************/
function onshowContact (dialog) {
	$(document).keypress(function(e){
	  var key  = (window.event) ?  event.keyCode : e.keyCode;
 	 if( key == 27 ) $.modal.close();
	});
	if($(contactForm_config.container).length) {
		
		/* Bind field checking events */		
		$(contactForm_config.container+" input[name='org'], #entry_contact input[name='type'], #entry_contact input[name='inquiry']")
			.blur(function(){checkField($(this),isCompleted,"Field Required.")});
		$(contactForm_config.container+" input[name='name']")
			.blur(function(){checkField($(this),isValidName,"Full Name Required.")});
		setOptional($(contactForm_config.container+" input[name='phone']"));
		$(contactForm_config.container+" select[name='contact_how']").change(function(){
			var phone = $(contactForm_config.container+" input[name='phone']");
			var email = $(contactForm_config.container+" input[name='email']");
			if ($(this).val() == "email") {
				clearOptional(email);	setOptional(phone);
			} else {
				clearOptional(phone);
				setOptional(email);
			}
		});
		
		/* Do fancy stuff for contact methods */
		$(contactForm_config.container+" input[name='email']").change(function(){
			var nullpasses = $(contactForm_config.container+" select[name='contact_how']").val() == "email" ? false : true;
			checkField($(this),isValidEmail,"Invalid email format. Please correct.",nullpasses);
		});	
		$(contactForm_config.container+" input[name='phone']").change(function(){
			var nullpasses = $(contactForm_config.container+" select[name='contact_how']").val() == "phone" ? false : true;
			checkField($(this),isValidPhone,"Phone numbers cannot contain letters (with the exception of 'ext'). Please correct.",nullpasses);
		});	
			
		/* SUBMIT */
		$(contactForm_config.container+" button[name='contact_send']").click(function(){
			/* Last shot at validation */
			$(contactForm_config.container+" input[name='org'], "+contactForm_config.container+" input[name='type'], "+contactForm_config.container+" input[name='inquiry']")
				.each(function(){checkField($(this),isCompleted,"Field Required.")});
			checkField($(contactForm_config.container+" input[name='name']"),isValidName,"Full Name Required.");
			var nullpasses = $(contactForm_config.container+" select[name='contact_how']").val() == "email" ? false : true;
			checkField($(contactForm_config.container+" input[name='email']"),isValidEmail,"Invalid email format. Please correct.",nullpasses);
			nullpasses = $(contactForm_config.container+" select[name='contact_how']").val() == "phone" ? false : true;
			checkField($(contactForm_config.container+" input[name='phone']"),isValidPhone,"Phone numbers cannot contain letters (with the exception of 'ext'). Please correct.",nullpasses);

			
			if ($('.form_error').length) {
				// Form fields empty!
				alert("Please complete all fields.");
			} else { 
				$(this).attr("disabled", "true");  // no submitting twice!
				data_string = $(contactForm_config.container+" form").serialize();
				// user feedback:
					$(contactForm_config.container+" form").append($('<p class="sending">Please wait while we send your message...</p>')); 
					name = $(contactForm_config.container+" input[name='name']").val();			
					$(contactForm_config.container).fadeTo(500,.5);
				$.ajax({
				   type: "POST",
				   url: "/scripts/ajax/contact_process.php",
				   data: data_string+"&title="+$("#q_title").text(),
				   async: false,
				   success: function(msg){
					$(contactForm_config.container+" h2").after(
						$("<p class='success column span-4 last'>Hello, <strong>"
							+ name	+"</strong>:<br />" + 
							"Thank you for your interest. You'll hear back from "+$("#q_name").text()+" soon.</p>")); 
					$(contactForm_config.container).fadeTo(500,1);
				   },
				   error: function(obj,text,error) {
					$(contactForm_config.container+" h2").after(
						$("<p class='error column span-4 last'>Hello, <strong>"
							+ name	+ "</strong>:<br />" + 
							"Something went wrong when we tried to send your message. You can try again later "
							+ "or contact us another way: by phone at +1.315.853.4900 or by e-mail at "
							+ "<a href='"+$(contactForm_config.container+" form").attr("title")+"?subject=Contact: "+$("#q_title").text()+"'>"
							+ $(contactForm_config.container+" form").attr("title")+"</a>.</p>")); 
					$(contactForm_config.container).fadeTo(500,1);
				   }
				 });

				$(contactForm_config.container+" form").remove();
			}
			return false; // We don't want to submit the form since AJAX handled it
		});
	}
}

/*****************************************
 Take Care of Processing the Friend Form
*****************************************/
function onshowFriend (dialog) {
	$(document).keypress(function(e){
	  var key  = (window.event) ?  event.keyCode : e.keyCode;
 	 if( key == 27 ) $.modal.close();
	});
	if($(friendForm_config.container).length) {
		$(friendForm_config.container+" input[name='sname'], "+friendForm_config.container+" input[name='rname']")
			.blur(function(){checkField($(this),isCompleted,"Field Required.")});
		$(friendForm_config.container+" input[name='remail'],"+friendForm_config.container+" input[name='semail']")
			.blur(function(){checkField($(this),isValidEmail,"Invalid email format. Please correct.")});

		$(friendForm_config.container+" button[name='friend_send']").click(function(){
	
			$(friendForm_config.container+" input[name='sname'], "+friendForm_config.container+" input[name='rname']")
				.each(function(){checkField($(this),isCompleted,"Field Required.")});
			$(friendForm_config.container+" input[name='remail'],"+friendForm_config.container+" input[name='semail']")
				.each(function(){checkField($(this),isValidEmail,"Invalid email format. Please correct.")});

			if ($('.form_error').length) {
				alert("Please complete all fields.");
			} else { 
				$(this).attr("disabled", "true");
				$(friendForm_config.container+" form").append($('<p class="sending">Please wait while we send your message...</p>'));
				data_string = $(contactForm_config.container+" form").serialize();
				$(friendForm_config.container).fadeTo(500,.5);
				$.ajax({
				   type: "POST",
				   url: "/scripts/ajax/friend_process.php",
				   data: data_string+"&ajax=true",
				   async: false,
				   success: function(msg){
					$(friendForm_config.container+" h2").after(
						$("<p class='success column span-4 last'>" 
							+ "Your friend has been sent an e-mail with a link to this post.</p>")); 
					$(friendForm_config.container).fadeTo(500,1);
				   },
				   error: function(obj,text,error) {
					$(friendForm_config.container+" h2").after(
						$("<p class='error column span-4 last'>Hello, <strong>"
							+ name	+ "</strong>:<br />" + 
							"Something went wrong when we tried to send your message. Please try again later.</p>")); 
					$(friendForm_config.container).fadeTo(500,1);
				   }
				 });

				$(friendForm_config.container+" form").remove();
			}
			return false; // We don't want to submit the form since AJAX handled it
		});
	}
}


/*****************************************
 Helper Fcns
*****************************************/
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars(u)
{
	var url = u=="" ? window.location.href : u;
	var vars = [], hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
jQuery.fn.addNotice = function(element, time) {
	jQuery(this).prepend(element);
	element.animate({opacity:1},time, function(){
		jQuery(this).animate( {opacity: 0.0, height:0}, 1000, function() {jQuery(this).remove();})
	});
	return this;
}
function isCompleted(str) { return str != ""; }
function isValidName(str) {
  var format = new RegExp("^.* .*$"); 
  var matches = format.exec(str);
  return matches;
}
function isValidEmail(str) {
  if (str == "optional") return true;
  var format = new RegExp("^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+[.])+[A-Za-z]{2,4}$"); 
  var matches = format.exec(str);
  return matches;
}
function isValidPhone(str) {
  if (str == "optional") return true;
  var format = new RegExp("^[-0-9ext,.\s ()+]+$"); 
  var matches = format.exec(str);
  return matches;
}
function checkField(element,check,error,nullpasses) {
	nullpasses = nullpasses ? (trim(element.val())=="" ? true : false) : false;
	element.removeClass('form_error');
	if (element.parent('div,p').children("span.error").length) 
			element.parent('div,p').children("span.error").remove();
	
	if (nullpasses || check(element.val())) return true; 
	
	element.addClass('form_error');
	$('<span class="error">'+error+'</span>').appendTo(element.parent('div,p'));
	return false;
									
}
function trim(str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function setOptional(el) {
	if (el.val() == "") el.val('optional').addClass('js_option');
	el.focus(function(){ if (el.val() == 'optional') el.val("").removeClass('js_option'); })
			 .blur(function(){ if (el.val() == "") el.val('optional').addClass('js_option'); }).change();	
}
function clearOptional(el) {
	if (el.val() == "optional") el.val("");
	el.removeClass('js_option').unbind('focus').unbind('blur');
}
jQuery.fn.pulse = function(time) {this.animate({opacity:.2},time).animate({opacity:1},time);return this;}

// ]]>
