
var orderStates = $H({AK:'AK', AL:'AL', AR:'AR', AZ:'AZ', CA:'CA', CO:'CO', CT:'CT', DC:'DC', 
					DE:'DE', FL:'FL', GA:'GA', HI:'HI', IA:'IA', ID:'ID', IL:'IL', IN:'IN', KS:'KY', 
					KY:'KY', LA:'LA', MA:'MA', MD:'MD', ME:'ME', MI:'MI', MN:'MN', MO:'MO', MS:'MS', 
					MT:'MT', NC:'NC', ND:'ND', NE:'NE', NH:'NH', NJ:'NJ', NM:'NM', NV:'NV', NY:'NY', 
					OH:'OH', OK:'OK', OR:'OR', PA:'PA', PR:'PR', RI:'RI', SC:'SC', SD:'SD', TN:'TN', 
					TX:'TX', OK:'UT', VA:'VA', VT:'VT', WA:'WA', WI:'WI', WV:'WV', WY:'WY'}); 

var orderProvinces = $H({AB:'Alberta', BC:'British Columbia', MB:'Manitoba', NB:'New Brunswick', 
						NL:'Newfoundland &amp; Labrador', NS:'Nova Scotia', NT:'Northwest Territories', 
						NU:'Nunavut', ON:'Ontario', PE:'Prince Edward Island', QC:'Quebec City', 
						SK:'Saskatchewan', YT:'Yukon'});

document.observe("dom:loaded", function() {
	if (document.body.className == "wss_ordernow") {
		// start with default US states
		populateStates('us');
		
		// focus firstname field
		$('first').focus();
		
		$('country').observe('change', function() {
			if ($('country').value == "can") {
				populateStates('can');
			}
			else if ($('country').value == "us") {
				populateStates('us');
			}
			// attach/reattach observer to state menu
			$('state').observe('change', function(e) {
				calcTax();
			});			
		});
		
		// quantity error checking
		$('quantity').observe('change', function(e) {
			var lastQuantity = $('lastquantity').value;
			
			// check to make sure that quantity input is valid
			if (!$('quantity').value.match(/[0-9]+/)) {
				$('quantity').value = lastQuantity;
				showError(1);
				return;
			}
			
			// good quantity, set last quantity to this quantity
			$('lastquantity').value = $('quantity').value;
			
			// subtotal
			var ajaxParameters = 'quantity=' + $('quantity').value + '&output=subtotal';
			new Ajax.Request('calcorder.php', {
				method:'get',
				parameters:ajaxParameters,
				onSuccess: function(transport) {
					$('subtotal').innerHTML = transport.responseText;
					new Effect.Highlight('subtotal', { startcolor:'#EF3E35', endcolor:'#ffffff', duration:1.0});
				}
			});
			if ($('country').value) {
				// shipping
				calcShipping();
			}
			if ($('state').value) {
				// tax, total
				calcTax();
			}
		});
		
		$('email').observe('change', function(e) {
			// email error checking
			if (!$('email').value.match(/^.+@.+\./)) {
				showError(3);
				return;
			}	
		});
		
		$('state').observe('change', function(e) {
			calcTax();
		});
		
		$('country').observe('change', function(e) {
			calcShipping(true);
		});
		
		$('witzorder').observe('submit', function(e) {
			var formVars = $H($('witzorder').serialize(true));

			// validate input
			var missingField;
			formVars.each(function(pair) {
				switch (pair.key) {
					// optional fields
					case 'title':
					case 'company':
					case 'phone2':
					case 'address2':
					case 'address3':
					case 'total':
					case 'totalsubtotal':
					case 'totalshipping':
					break;
					
					default:
					if (!pair.value) {
						missingField = true;
					}
					break;
				}
			});
			
			if (missingField) {
				showError(2);
				e.stop();				
			}
			else {
				// move totaltmp -> total
				$('total').value = $('totaltmp').value;
				$('totalsubtotal').value = $('totalsubtotaltmp').value;
				$('totalshipping').value = $('totalshippingtmp').value;			
				
				if (!$('email').value.match(/^.+@.+\./)) {
					showError(3);
					return;
				}
				
				var ajaxParameters = $('witzorder').serialize() + '&totalgst=' + $('totalgst').value + '&totalpst=' + $('totalpst').value + '&checkout=1';
				new Ajax.Request('orderform.php', {
					method:'get',
					parameters:ajaxParameters,
					onSuccess: function(transport) {
						if (!transport.responseText == 'success') {
							// MySQL error
							Modalbox.show('<div class=\'warning\'>Your order cannot be completed, please contact us for assistance</div>', { title:'ERROR', width:500, overlayClose:false });
						}
						else {
							// make complete order button hidden
							$('submitbutton').setStyle({visibility:'hidden'});
							//$('total').value = 0.01;   // for testing
							
							var ppURL = 'https://www.paypal.com/xclick/business=smartsales@witztraining.com&item_name=Witz Smart Sales Order&amount=' + $('total').value + '&no_shipping=1&return=http://witzsmartsales.com/thanks.php&cancel_return=http://witzsmartsales.com/orderform.php&currency_code=CAD';
							window.location.href = ppURL;
						}					
					}
				});
				e.stop();
			}
		});
	}
	
	if (document.body.className == "wss_assessment") {
		$('submit').observe('click', function(e) {
			var FirstMissingField;
			var formVals = $('assform').serialize(true);
			$H(formVals).each(function(pair){
				if ((!pair.value && pair.key !== "company" && pair.key !== "industrysector") 
					|| (pair.key == "cemail" && !$('cemail').value.match(/^.+@.+\./))) {
					// mark field as missing
					$(pair.key + '_label').setStyle({color:'#EF3E35'});
					if (!FirstMissingField) {
						FirstMissingField = pair.key + '_label';
					}
				}
			});
			if (FirstMissingField) {
				// display error message
				showError(2);
				new Effect.ScrollTo(FirstMissingField, { duration:1 });
				e.stop();
			}
		});
		
		$('cemail').observe('change', function(e) {
			// email error checking
			if (!$('cemail').value.match(/^.+@.+\./)) {
				showError(3);
				return;
			}	
		});
	}
});

function calcTax() {
	// tax
	var ajaxParameters = 'quantity=' + $('quantity').value + '&state=' + $('state').value + '&country=' + $('country').value + '&output=tax';
	new Ajax.Request('calcorder.php', {
		method:'get',
		parameters:ajaxParameters,
		onSuccess: function(transport) {
			$('tax').innerHTML = transport.responseText;
			new Effect.Highlight('tax', { startcolor:'#EF3E35', endcolor:'#ffffff', duration:1.0});
		}
	});
	// total
	var ajaxParameters = 'quantity=' + $('quantity').value + '&state=' + $('state').value + '&country=' + $('country').value + '&output=total';
	new Ajax.Request('calcorder.php', {
		method:'get',
		parameters:ajaxParameters,
		onSuccess: function(transport) {
			$('totaldisplay').innerHTML = transport.responseText;
			new Effect.Highlight('totaldisplay', { startcolor:'#EF3E35', endcolor:'#ffffff', duration:1.0});
		}
	});
}

function calcShipping(resetTotals) {
	var ajaxParameters = 'quantity=' + $('quantity').value + '&country=' + $('country').value + '&output=shipping';
	new Ajax.Request('calcorder.php', {
		method:'get',
		parameters:ajaxParameters,
		onSuccess: function(transport) {
			$('shipping').innerHTML = transport.responseText;
			new Effect.Highlight('shipping', { startcolor:'#EF3E35', endcolor:'#ffffff', duration:1.0});
			if (resetTotals) {
				$('tax').innerHTML = '';
				$('totaldisplay').innerHTML = '';	
			}
		}
	});
}

function populateStates(country) {
	var stateHTML = '<select class = "menu" name = "state" id = "state">\n<option value = ""></option>';	
	if (country == "us") {
		orderStates.each(function(pair) {
			stateHTML += '<option value = "' + pair.key + '">' + pair.value + '</option>\n';
		});
	}
	else if (country == "can") {
		orderProvinces.each(function(pair) {
			stateHTML += '<option value = "' + pair.key + '">' + pair.value + '</option>\n';
		});
	}
	stateHTML += '</select>\n';
	$('statemenu').innerHTML = stateHTML;
}

function showError(errorID) {
	switch (errorID) {
		case 1:
		// invalid quantity
		Modalbox.show('<div class=\'warning\'>Please enter a valid quantity</div>', { title:'ERROR', width:500, overlayClose:false });
		break;
		
		case 2:
		// missing fields
		Modalbox.show('<div class=\'warning\'>You are missing some required fields</div>', { title:'ERROR', width:500, overlayClose:false });
		break;
		
		case 3:
		// invalid email address
		Modalbox.show('<div class=\'warning\'>Invalid email address</div>', { title:'ERROR', width:500, overlayClose:false });
		break;		
	}
}