﻿ForensicDigital = function () {

	this.windowOpen = function (a) {
		var w;
		try { w = window.open(a.href); } catch (e) {}	//	attempt popup
		if (!w)
			location.href = a.href;	//	popup failed, navigate current window
		return false;
	};

	this.formResponseHandler = function (form, json) {
		if (json.alert)
			alert(json.alert);

		if (json.reset)
			form.reset();
	};

	this.onAllWindowLoad = function (evt) {
		
		var contactForm = $('contactForm');
		if (contactForm)	//	attach to contact form if there's one on the page
			Event.observe(contactForm, 'submit', this.contactFormOnSubmit.bindAsEventListener(this));

		var bookingForm = $('bookingForm');
		if (bookingForm)	//	attach to booking form if there's one on the page
			Event.observe(bookingForm, 'submit', this.bookingFormOnSubmit.bindAsEventListener(this));
	};
	
	Event.observe(window, 'load', this.onAllWindowLoad.bind(this));	//	attach to all window onloads

	this.contactFormOnSubmit = function (evt) {
		Event.stop(evt);
		var form = Event.element(evt);
		while (form.nodeName != "FORM")
			form = form.up();
		form.request({
			onComplete: this.contactFormOnComplete.bind(this, form),
			onFailure: this.contactFormOnFailure.bind(this, form),
			onSuccess: this.contactFormOnSuccess.bind(this, form)
		});
		form.disable();
	};
	
	this.contactFormOnSuccess = function (form, xhr) {
		var json = xhr.responseText.evalJSON(true);
		if (json)
			this.formResponseHandler(form, json);
	};
	
	this.contactFormOnFailure = function (form, xhr) {
		alert("An error occurred when processing your request. Please try again later.");
	};
	
	this.contactFormOnComplete = function (form, xhr) {
		form.enable();
	};

	this.bookingFormOnSubmit = function (evt) {
		Event.stop(evt);
		var form = Event.element(evt);
		while (form.nodeName != "FORM")
			form = form.up();
		form.request({
			onComplete: this.bookingFormOnComplete.bind(this, form),
			onFailure: this.bookingFormOnFailure.bind(this, form),
			onSuccess: this.bookingFormOnSuccess.bind(this, form)
		});
		form.disable();
	};

	this.bookingFormOnSuccess = function (form, xhr) {
		var json = xhr.responseText.evalJSON(true);
		if (json)
			this.formResponseHandler(form, json);
	};
	
	this.bookingFormOnFailure = function (form, xhr) {
		alert("An error occurred when processing your request. Please try again later.");
	};
	
	this.bookingFormOnComplete = function (form, xhr) {
		form.enable();
	};

};

forensicDigital = new ForensicDigital();
