$(function(){

	var links = $("a.contact-ajax");
	if (links.length) {
		links.click(function(){
			/// fix contact page form conflict
			if ($("body.contact").length){
				$("#contact_form").attr('id','contact_form_page');
				$("#contact_form_page :input").each(function(){
					$(this).attr("id",$(this).attr("id")+"_page");
				});
				$("#contact_form_page label").each(function(){
					$(this).attr("for",$(this).attr("for")+"_page");
				});
			}
			
			ajaxFailed = true;
			$.ajax({
			   type: "POST",
			   url: "/assets/scripts/ajax/contact_form.php",
			   data: "pagename="+encodeURI($("h2:eq(0)").text()),
			   async: false,
			   success: function(msg){
				   var form = $(msg);
				   
				   form.modal({onClose: closeModal, onOpen: openModal, persist: false, onShow: onshowModal});
				   
				   ajaxFailed = false;
			   },
			   error: function(obj,text,error) {   }
		 	});
			
			return ajaxFailed;
		});
	}
});


function openModal (dialog) {
	dialog.overlay.fadeIn('slow', function () {
		dialog.container.slideDown('slow', function () {
			dialog.data.fadeIn('slow');
		});
	});
}

function closeModal (dialog) {
	dialog.data.fadeOut('slow', function () {
		dialog.container.slideUp('slow', function () {
			dialog.overlay.fadeOut('slow', function () {
				$.modal.close(); // must call this!
			});
		});
	});
				/// fix contact page form conflict
			if ($("body.contact").length){
				$("#contact_form_page").attr('id',$("#contact_form_page").attr('id').replace("_page",""));
				$("#contact_form :input").each(function(){
					$(this).attr("id",$(this).attr("id").replace("_page",""));
				});
				$("#contact_form label").each(function(){
					$(this).attr("for",$(this).attr("for").replace("_page",""));
				});
			}

}

function onshowModal (dialog) {
	if($("#contact_form").length) {
		
		/* Bind field checking events */		
		$("#type, #org, #inquiry")
			.blur(function(){checkField($(this),isCompleted,"Field Required.")});
		$("#name")
			.blur(function(){checkField($(this),isValidName,"Full Name Required.")});

		setOptional($("#phone"));
		$("#contact_how").change(function(){
			var phone = $("#phone");
			var email = $("#email");
			if ($(this).val() == "email") {
				clearOptional(email);	setOptional(phone);
			} else {
				clearOptional(phone);
				setOptional(email);
			}
		});
		
		/* Do fancy stuff for contact methods */
		$("#email").change(function(){
			var nullpasses = $("#contact_how").val() == "email" ? false : true;
			checkField($(this),isValidEmail,"Valid address required.",nullpasses);
		});	
		$("#phone").change(function(){
			var nullpasses = $("#contact_how").val() == "phone" ? false : true;
			checkField($(this),isValidPhone,"Valid number required.",nullpasses);
		});	


		/* SUBMIT */
		$("#contact_form").submit(function(){
			/* Last shot at validation */
			$("#type, #org, #inquiry,#contact,#contact_how")
				.each(function(){checkField($(this),isCompleted,"Field Required.")});
			checkField($("#name"),isValidName,"Full Name Required.");

			var nullpasses = $("#contact_how").val() == "email" ? false : true;
			checkField($("#email"),isValidEmail,"Valid address required.",nullpasses);
			nullpasses = $("#contact_how").val() == "phone" ? false : true;
			checkField($("#phone"),isValidPhone,"Valid number required.",nullpasses);
			
			if ($('.form_error').length) {
				// Form fields empty!
				alert("Please complete all fields.");
			} else { 
				data_string = $("#contact_form").serialize();
				// user feedback:
					$("#contact_form").append($('<p class="sending">Please wait while we send your message...</p>')); 
					name = $("#name").val();			
					$("#contact_form").fadeTo(500,.5);
				$.ajax({
				   type: "POST",
				   url: "/assets/scripts/contact.php",
				   data: data_string+"&page="+$("#page-name").text(),
				   async: false,
				   success: function(msg){
					$("#contact-form-container h2").after(
						$("<p class='success'>Hello, <strong>"
							+ name	+"</strong>:<br />" + 
							"Thank you for your interest in the Herkimer County Industrial Agency. You will be contacted within 1-2 business days.</p>")); 
				   },
				   error: function(obj,text,error) {
					$("#contact-form-container h2").after(
						$("<p class='error'>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 (315) 867-1373 or by e-mail at "
							+ "<a href='mailto:ida@herkimercounty.org?subject=Herkimer County IDA Website Inquiry'>ida@herkimercounty.org</a>.</p>")); 
				   }
				 });

				$("#contact_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;}

