/* Modal dialog for transfer page */
$(function(){
   var exits = $("a[href^='/exit.php']");
   if (exits && exits.length) {		   
	exits.click(function(){
		var url = getUrlVars($(this).attr("href"));
		var modalsuccess = false;
		$.ajax({
		   type: "GET",
		   url: "/assets/scripts/modal-exit.inc.php",
		   data: "return="+window.location.href+"&d="+url['d'],
		   async: false,
		   success: function(msg){
				if (msg!="") {
					$(msg).appendTo('body');
					$("#modal").modal({close: false, onClose: modalClose, onOpen: modalOpen, persist: false, position: [1,]});
					modalsuccess = true;
				} 
		   },
		   error: function(obj,text,error) { }
		 });
		 
		 return !modalsuccess;
	});
   }
});


/* Modal contact form */
$(function(){
   var contacts = $("a[href^='/contact/?']");
   if (contacts && contacts.length) {		   
	contacts.click(function(){
		var url = getUrlVars($(this).attr("href"));
		var modalsuccess = false;
		$.ajax({
		   type: "GET",
		   url: "/assets/scripts/contact_form.inc.php",
		   data: "recipient="+url['r'],
		   async: false,
		   success: function(msg){
				if (msg!="") {
					$(msg).appendTo('body');
					$("#contact").append($('<a href="'+window.location.href+'" class="simplemodal-close inform-close">Close</a>'))
						.modal({close: false, onClose: modalClose, onOpen: modalOpen, onShow: onshowContact, persist: false, position: [1,]});
					modalsuccess = true;
				} 
		   },
		   error: function(obj,text,error) { }
		 });
		 
		 return !modalsuccess;
	});
   }
});


// Print statement swapper
$(function() { 
	var printer = $("#print-page");	   
	if (printer && printer.length > 0) {
		printer.text("Click here to print this page").addClass("enhanced").click(function(){				   
			window.print();
		});
	}
});


/******************
	HELPER FUNCTIONS
	*******************/
function modalOpen(dialog) {
	dialog.overlay.fadeIn('fast', function () {
		dialog.data.hide();
		dialog.container.fadeIn('fast', function () {
			dialog.data.slideDown('fast');
		});
	});
}
function modalClose(dialog) {
	dialog.data.fadeOut('fast', function () {
		dialog.container.hide('fast', function () {
			dialog.overlay.slideUp('fast', function () {
				$.modal.close();
				$("#modal,#contact").remove();
			});
		});
	});
	
}
function onshowContact(dialog) {
	// catch escape key to close modal window
	$(document).keypress(function(e){
	  var key  = (window.event) ?  event.keyCode : e.keyCode;
 	 if( key == 27 ) modalClose(dialog);    });

    /*bofu added these 3 lines on 10-19-2010 to highlight the fields in pink to indicate required when the form loaded*/    $("#contact input[name='inquiry']").addClass('form_error');    $("#contact input[name='name']").addClass('form_error');
    $("#contact input[name='email']").addClass('form_error');

	if($("#contact").length) {
		/* Bind field checking events */		
		$("#contact input[name='inquiry']")
			.blur(function(){checkField($(this),isCompleted,"Field Required.")});
		$("#contact input[name='name']")
			.blur(function(){checkField($(this),isValidName,"Full Name Required.")});
		setOptional($("#contact input[name='phone']"));
		$("#contact select[name='contact_how']").change(function(){
			var phone = $("#contact input[name='phone']");
			var email = $("#contact input[name='email']");
			if ($(this).val() == "email") {
			    clearOptional(email); setOptional(phone);
                email.addClass('form_error')	                /*bofu added on 10-19-2010 */
			} else {
                clearOptional(phone); setOptional(email);
                phone.addClass('form_error')                    /*bofu added on 10-19-2010 */
			}
		});
		/* Do fancy stuff for contact methods */
		$("#contact input[name='email']").change(function(){
			var nullpasses = $("#contact select[name='contact_how']").val() == "email" ? false : true;
			checkField($(this),isValidEmail,"Invalid email format. Please correct.",nullpasses);
		});	
		$("#contact input[name='phone']").change(function(){
			var nullpasses = $("#contact 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 */
		$("#contact form").submit(function(){
			/* Last shot at validation */
			$("#contact input[name='inquiry']")
				.each(function(){checkField($(this),isCompleted,"Field Required.")});
			checkField($("#contact input[name='name']"),isValidName,"Full Name Required.");
			var nullpasses = $("#contact select[name='contact_how']").val() == "email" ? false : true;
			checkField($("#contact input[name='email']"),isValidEmail,"Invalid email format. Please correct.",nullpasses);
			nullpasses = $("#contact select[name='contact_how']").val() == "phone" ? false : true;
			checkField($("#contact 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 = $("#contact form").serialize();
				// user feedback:
					$("#contact form").append($('<p class="sending">Please wait while we send your message...</p>')); 
					name = $("#contact input[name='name']").val();			
					$("#contact").fadeTo(500,.5);
				$.ajax({
				   type: "POST",
				   url: "/assets/scripts/contact_process.php",
				   data: data_string,
				   async: false,
				   success: function(msg){
					$("#contact h2").after(
						$("<p class='success'>Hello, <strong>"
							+ name	+"</strong>:<br />" + 
							"Thank you for your interest. You'll hear back from "+$("#q_name").text()+" as soon as possible.</p>")); 
					$("#contact").fadeTo(500,1);
				   },
				   error: function(obj,text,error) {
					$("#contact 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 by phone at (315) 797-2700 or (800) 442-1028.</p>")); 
					$("#contact").fadeTo(500,1);
				   }
				 });

				$("#contact form").remove();
			}
			return false; // We don't want to submit the form since AJAX handled it
		});
	}
}
// Read 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');
}

