(function($, Mage) {
	$(document).ready(function(){
			// -------------------------------------------------------------------------
			// INLINE  CONTACT FORMS
			// 
			// Convert all elements with contact-link class to an inline ajax form
			// http://www.position-absolute.com/articles/$-form-validator-because-form-validation-is-a-mess/
			// -------------------------------------------------------------------------

			// If there are no contact form links, don't do anything
			if (!$('.contact-link')) { return; }

			// Default value - this variable becomes the target form
			var $form = $;

			// Inject form into document body
			$.get(Mage.getBaseUrl() +'contact/dialog', function(data) {
				$('body').append(data);
				
				$("#inline-contact").dialog({
					width: 580,
					height: 620,
					resizable: false,
					modal: true,
					autoOpen: false,
					buttons: {
						'Send Message': contact_dialog_submit
					},
					close: contact_dialog_close
				});

				$form = $("#inline-contact .contact-form");
			});


			function contact_dialog_submit() {
				var valid = $form.validationEngine({ returnIsValid:true });
				if (!valid) { return(false); }

				$.ajax({
					url: $form.attr('action'),
					type: "POST",
					data: $form.serialize(),
					success: function(data, status, xhr) {
						if (data != 'success') {
							alert(data);
						}

						$("#inline-contact").dialog('close');
						$form.get(0).reset();
					},
					error: function(xhr, status, exception){
						console.log(xhr, status, exception);
						alert('There was an error while sending your message');
					}
				});

				return(false);
			}

			function contact_dialog_close(event, ui) {
				$.validationEngine.closePrompt('.formError', true)
				$form.get(0).reset();
			}


			$(".contact-link").click(function() {
				$form.attr('action', this.href);
				$form.validationEngine({
					scroll: false,
					success: false
				});

				var title = this.title.replace('Contact','');
				var title_html = ((title=='') ?  'Send a message' : 'Send a message to: <span style="font-weight: normal; margin-left: 4px">' + title + '</span>');
				$("#inline-contact").dialog({ title: title_html });

				$("#inline-contact").dialog('open');

				return(false);
			});
			
	}); // end document.ready
})(jQuery, Mage)


