Event.observe(window, 'load', function() {
  	Event.observe('order_form', 'submit', generateTotals);
	Event.observe('country', 'change', function () {
		if ($F('country') == 'US') {
			$('state_dropdown').show();
			$('state_text').hide();
		} else {
			$('state_dropdown').hide();
			$('state_text').show();
		}
	})
});

function generateTotals(eventid){
	Event.stop(eventid);
	var reason = "";
	reason += validateInteger($F('qty'));
	reason += validateEmail($('email'));
	reason += validatePhone($('phone'));
	reason += validateEmpty($('firstname'), "Firstname");
	reason += validateEmpty($('lastname'), "Lastname");
	reason += validateEmpty($('address'), "Address");
	reason += validateEmpty($('city'), "City");
	if ($F('country') != 'US') {
		reason += validateEmpty($('state_text'), "State");
	}
	reason += validateEmpty($('zipcode'), "Zipcode");
	reason += validateEmpty($('phone'), "Phone Number");
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
	}
	else {
		var myAjax = new Ajax.Request('generatetotals.php', {
			method: 'get',
			parameters: Form.serialize('order_form') + '&qty=' + $F('qty'),
			onSuccess: function(originalResponse){
				new Effect.Appear('showcart');
				JSONresponse = originalResponse.responseJSON;
				$('showcart').update(JSONresponse.previewHTML);
				Event.observe('submitorder', 'click', processOrder);	
			}
		});
	}
}

function processOrder(eventid){
	Event.stop(eventid);
	var reason = "";
	reason += validateInteger($F('qty'));
	reason += validateEmail($('email'));
	reason += validatePhone($('phone'));
	reason += validateEmpty($('firstname'), "Firstname");
	reason += validateEmpty($('lastname'), "Lastname");
	reason += validateEmpty($('address'), "Address");
	reason += validateEmpty($('city'), "City");
	if ($F('country') != 'US') {
		reason += validateEmpty($('state_text'), "State");
	}
	reason += validateEmpty($('zipcode'), "Zipcode");
	reason += validateEmpty($('phone'), "Phone Number");
	if (reason != "") {
		alert("Some fields need correction:\n" + reason);
	} else {
		var myNewAjax = new Ajax.Request('process.php', { method: 'post', parameters: Form.serialize('order_form') + '&qty='+$F('qty')
			, onSuccess: function (originalResponse) {
			JSONresponse = originalResponse.responseJSON;
			location.href=JSONresponse.mygourl;
			}
		});	
	}
}

function validateEmpty(fld,theinfo) {
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "--  " + theinfo + " is empty.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

function trim(s) {
  return s.replace(/^\s+|\s+$/, '');

}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "--  Email address is empty.\n";
    } else if (!emailFilter.test(tfld)) {
        fld.style.background = 'Yellow';
        error = "-- Email address is invalid.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "-- Email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    
   if (fld.value == "") {
        error = "--  Phone number.\n";
        fld.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "-- Phone number contains illegal characters.\n";
        fld.style.background = 'Yellow';
    } else if (!(stripped.length == 10)) {
        error = "-- Phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'Yellow';
    }
    return error;
}

function validateInteger (s) {
	var i;
	var error = "";
    if (s.length == 0) {
		error = "-- Please enter a valid quantity.\n";
	}
	else {
		for (i = 0; i < s.length; i++) {
			var c = s.charAt(i);
			if (!isDigit(c)) 
				error = "-- Please enter a valid quantity.\n";
		}
	}
	return error;
}

function isDigit (c) {
	return ((c >= "0") && (c <= "9"));
}