var DELIVERY_BASE = 2;
var DELIVERY_EXTRA = 1;
var DELIVERY_UNIT = " business days";
var PRICE_BASE = 290;
var PRICE_EXTRA = 140;
var CURRENCY_SIGN = "$";
var MSG_EMAIL = "Please, specify valid email address.";
var MSG_MESSAGE = "Please, specify your message.";
var MSG_FILE = "Please, specify the design file.";
var ID_EMAIL = "email";
var ID_MESSAGE = "message";
var ID_FILE = "template";
var ID_PAGES = "pages";
var ID_SUMMARY = "summary";


function initPage()
{
	var form = document.forms[0];
	if (form)
	{
		form.onsubmit = function ()
		{
			var email = document.getElementById(ID_EMAIL);
			if (!isEmail(email.value))
			{
				try { email.focus() } catch(e) {};
				alert(MSG_EMAIL);
				return false;
			}
			var message = document.getElementById(ID_MESSAGE);
			if (message && message.value == "")
			{
				try { message.focus() } catch(e) {};
				alert(MSG_MESSAGE);
				return false;
			}
			var file = document.getElementById(ID_FILE);
			if (file && file.value == "")
			{
				try { file.focus() } catch(e) {};
				alert(MSG_FILE);
				return false;
			}
			return true;
		}
	}

	var pages = document.getElementById(ID_PAGES);
	if (pages)
	{
		pages.onkeyup = function () { 
				if (isNaN(this.value) && this.value != "")
					this.value = 1;
				calculatePrice();
			}
		pages.onblur = function () {
				if (isNaN(this.value) || Number(this.value) < 1)
					this.value = 1;
				calculatePrice();
			}
	}
}

function calculatePrice()
{
	var sum = PRICE_BASE;
	var del = DELIVERY_BASE;
	var pe = document.getElementById(ID_PAGES);
	var pn = 1;
	if (!(isNaN(pe.value) || Number(pe.value) < 1))
		pn = Number(pe.value);
	if (pn > 1)
	{
		sum += Math.floor((pn - 1) * PRICE_EXTRA);
		del += (pn - 1) * DELIVERY_EXTRA;
	}
	var nodes = document.getElementById(ID_SUMMARY).getElementsByTagName("dd");
	var delivery = nodes.item(0);
	var total = nodes.item(1);
	delivery.innerHTML = del + DELIVERY_UNIT;
	total.innerHTML = CURRENCY_SIGN + sum;
}

function isEmail(email)
{
	return !(email == "" ||
		!email.match(new RegExp('^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$')));
}