function initForms(){
	$('label.req').prepend('<span class="required">* </span>');
	$('textarea').keyup(function(){
		var max = $(this).attr('maxlength');
		if (typeof(max) !== 'undefined' && this.value.length > max){
			this.value = this.value.substr(0, max);
			if(this.setSelectionRange){
				this.focus();
				this.setSelectionRange(max,max);
				this.scrollTop = this.scrollHeight;
			} else if (this.createTextRange) {
				this.collapse(false);
			}
			this.scrollTop = this.scrollHeight;
		}
	});
	$('#reload').click(function(){
		$('#captcha').attr('src', '/securimage/securimage_show.php?' + Math.random()); 
		return false;
	});
}	
function initCharity(){
	$('#hats, #state, #donation').change(function(){
		calculateTotal();
	});
	$('#donation').focus(function(){
		if (this.value == '$') this.value = '';
	});
	$('#donation').blur(function(){
		if (this.value == '') this.value = '$';
	});
	$('#buynow').click(function(e){
		trimInput();
		var msg = '';
		msg += validate('fname', true, rx.name);
		msg += validate('lname', true, rx.name);
		msg += validate('company', false, rx.addr);
		msg += validate('addr', true, rx.addr);
		msg += validate('city', true, rx.name);
		msg += validate('state', true);
		msg += validate('zip', true, rx.zip);
		msg += validate('email', true, rx.email);
		msg += validate('hats', true);
		msg += validate('donation', false, rx.money);
		//msg += validateCaptcha();
		msg += validate('agree', true);
		if (checkForm(msg)==true){
			calculateTotal();
			return true;
		} else {
			return false;
		}
	});
}

function calculateTotal(){
	var zones = [['AR','AZ','CA','CO','IA','ID','IL','KS','LA','MN','MO','MT','ND','NE','NM','NV','OK','OR','SD','TX','UT','WA','WI','WY'],
		['AL','CT','DC','DE','FL','GA','IN','KY','MA','MD','ME','MI','MS','NC','NH','NJ','NY','OH','PA','RI','SC','TN','VA','VT','WV'],
		['AK','HI']];
	var qtys = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]];
	var rates = [[7.5,8,9], [10.25,11.25,12], [19,20.25,23]];
	var shipping = 0;
	var cost = 19.95;
	var hats = $('#hats :selected').val() == '' ? 0 : $('#hats :selected').val();
	var color = $('#color :selected').val();
	var merch = (hats*cost);

	if (hats != 0 && $('#state :selected').val() != ''){
		for (i=0; i<zones.length; i++){
			for (j=0; j<zones[i].length; j++){
				if ($('#state :selected').val() == zones[i][j]) x=i;
			}
		}
		for (i=0; i<qtys.length; i++){
			for (j=0; j<qtys[i].length; j++){
				if (hats == qtys[i][j]) y=i;
			}
		}
		shipping = rates[x][y];
	}
	var nodollar = parseFloat($('#donation').val().replace(/[\$,]/g,''));
	//var nodollar = $('#donation').val().replace(/[\$,]/g,'');
	if (!isNaN(nodollar)){
		merch += nodollar;
	} else {
		$('#donation').val('$')
	}
	var item = "Total tax deductible donation is $" + merch.toFixed(2);
	if(hats > 1) {
		item = "Order of " + hats + " " + color + " VCA WOOF Hats + shipping. Total tax deductible donation is $" + merch.toFixed(2);
	}
	else if(hats == 1) {
		item = "Order of " + hats + " " + color + " VCA WOOF Hat + shipping  Total tax deductible donation is $" + merch.toFixed(2);
	}
	if (!isNaN(merch)) {
  	$('#merch').text('$' + merch.toFixed(2));
  }
	if (!isNaN(shipping)) {
  	$('#sandh').text('$' + shipping.toFixed(2));
  }
	$('input[name=item_name]').val(item);
	$('input[name=amount]').val(merch.toFixed(2));
	$('input[name=os0]').val(hats);
	$('input[name=shipping]').val(shipping.toFixed(2));
}

function initTestimonials(){
	$('#optin').click(function(){
		var label = $('label[for=email]');
		if (label.find('span.required').is(':first-child')){
			label.removeClass('in-error').find('span.required').remove();
		}
		else {
			label.prepend('<span class="required">* </span>');
		}
	});
	$('#submit').click(function(e){
		trimInput();
		var msg = '';
		msg += validate('name', true, rx.name);
		msg += validate('city', true, rx.addr);
		msg += validate('state', true);
		msg += validate('title', true, rx.name);
		msg += validate('testimonial', true);
		msg += validate('email', $('#optin').is(':checked'), rx.email);
		msg += validate('petname', false, rx.name);
		msg += validate('agree', true);
		//msg += validateCaptcha();
		return checkForm(msg);
	});
}

function initAppt(){
	var isPCC = false;
	var enddate = new Date("March 31, 2010");
	$('#date1, #date2, #date3').datepicker({ 
		beforeShowDay:function(date){
			isPCC = $('#pcc').val() == 'true' && $('#pcc-day').val() != '7';
			if (!isPCC){
				return [true, ''];
			}
			else {
				var day = date.getDay();
				var days = $('#pcc-day').val().split(',');
				for (i = 0; i < days.length; i++) {
					if (day == days[i]) {
						return [true, ''];
					}
				}
				return [false, ''];
			}
		},
		maxDate: isPCC ? enddate : null
	});
	$('#pettype').change(function(){
		//alert('change');
		if ($(this).val()=='Other'){
			//alert('woohoo');
			$('#other').removeAttr('disabled');
		} else {
			$('#other').val('').attr('disabled', 'disabled');
		}
	});
	$('#date1, #date2, #date3').change(function(){
		if ($(this).val() != ''){
			$('#'+this.id.replace('date', 'time')).removeAttr('disabled');
		} else {
			$('#'+this.id.replace('date', 'time')).attr('disabled', 'disabled');
		}
	});
	$('#submit').click(function(e){
		var isPCC = $('#pcc').val() == 'true' && $('#pcc-day').val() != '7';
		//return true;
		trimInput();
		var msg = '';
		msg += validate('fname', true, rx.name);
		msg += validate('lname', true, rx.name);
		msg += validate('phone', true, rx.phone);
		msg += validate('altphone', false, rx.phone);
		msg += validate('email', true, rx.email);
		msg += validate('other', false, rx.name);
		msg += validate('petname', false, rx.name);
		msg += validate('petage', false, rx.addr);
	
		if (isPCC){
			msg += matchDateTime(1,true);
			msg += matchDateTime(2,false);
			msg += matchDateTime(3,false);
		}
		else  {
			msg += checkDate('date1', true);
			msg += validate('time1', false, rx.time);
			msg += checkDate('date2', false);
			msg += validate('time2', false, rx.time);
			msg += checkDate('date3', false);
			msg += validate('time3', false, rx.time);
		}
		//msg += validate('reason', true);
		//msg += validateCaptcha();
		msg += validate('agree', true);
		
		
		return checkForm(msg);
	});
}

function initOffer(){
	$('#a-newmex').click(function(){
		$('#a-newmex strong, #img-newmex img, #p-newmex span').toggle();
		$('#newmex').val($('#newmex').val() == '0' ? '1' : '0');
		return false;
	});
	$('#submit').click(function(e){
		trimInput();
		var msg = '';
		msg += validate('fname', true, rx.name);
		msg += validate('lname', true, rx.name);
		msg += validate('addr', false, rx.addr);
		msg += validate('city', false, rx.name);
		msg += validate('zip', true, rx.zip);
		msg += validate('phone', false, rx.phone);
		msg += validate('email', true, rx.email);
		msg += validate('other', false, rx.name);
		msg += validate('petname', false, rx.name);
		msg += validate('petage', false, rx.addr);
		msg += validate('agree', true);
		//msg += validateCaptcha();
		return checkForm(msg);
	});
}

function initContactUs(){
	$(':radio[name=method]').click(function(){
		var label = $('label[for=phone]');
		if ($(this).is('[value=phone]:checked')){
			label.prepend('<span class="required">* </span>');
		} else {
			label.removeClass('in-error').find('span.required').remove();
			$('#phone').removeClass('in-error');
		}
	});
	$('#submit').click(function(e){
		trimInput();
		var msg = '';
		msg += validate('fname', true, rx.name);
		msg += validate('lname', true, rx.name);
		msg += validate('reason', true);
		msg += validate('email', true, rx.email);
		msg += validate('phone', $(':radio[name=method][value=phone]').is(':checked'), rx.phone);
		msg += validate('message', true);
		msg += validateCaptcha();
		return checkForm(msg);
	});
}

function validate(id, req, regex){
	var field = $('#'+id);
	var label = $('label[for='+id+']');
	var textbox = field.is(':text') || field.is('textarea') || field.is(':password'); 
	var checkbox = (field.is(':checkbox') || field.is(':radio'));
	var selectbox = field.is('select');
	var msg = '';
	if (req && ((textbox && field.val().length === 0) || (checkbox && !field.is(':checked')) || (selectbox && field.val().length === 0))){
		field.add(label).addClass('in-error');
		msg += label.find('span.msg-req').html() + '<br />';
	}
	else if (textbox && field.val().length > 0 && regex && !regex.test(field.val())){
		field.add(label).addClass('in-error');
		msg += label.find('span.msg').html() + '<br />';
	}
	else {
		field.add(label).removeClass('in-error');
	}
	return msg;
}

function validateCaptcha(){
	var msg = $.ajax({
		type: 'GET',
		async: false,
		url: '/_class/Secureimage.php?captcha_code='+$('#captcha_code').val(),
		dataType: 'text'
	}).responseText;
	if (msg !== '') {
		msg += '<br />';
		$('label[for=captcha_code]').addClass('in-error');
	} else {
		$('label[for=captcha_code]').removeClass('in-error');
	}
	return msg;
}

function checkForm(msg){
	if (msg !== '') {
		$('#error-msg').html(msg).show();
		$('#reload').trigger('click');
		$('#captcha_code').val('');
		return false;
	} else {
		$('#js').val($('#token').val());
		$('#error-msg').html('').hide();
		cleanInput();
		return true;
	}
}

function checkDate(id, req){
	var msg = '';
	msg += validate(id, req, rx.date)
	if (msg == '') {
		var field = $('#' + id);
		var label = $('label[for=' + id + ']');
		var form = new Date(field.val());
		var today = new Date();
		if (form.getTime() <= today.getTime()) {
			field.add(label).addClass('in-error');
			msg += label.find('span.msg-date').html() + '<br />';
		}
		else {
			field.add(label).removeClass('in-error');
		}
	}
	return msg;
}

function matchDateTime(idx, req){
	var msg = '';
	var datefield = $('#date'+idx);
	msg += checkDate('date'+idx, req);
	msg += validate('time'+idx, false, rx.time);
	if (datefield.val() != '' && msg==''){
		var str = "March 31, 2010";
		var enddate = new Date("March 31, 2010");
		var timefield = $('#time'+idx);
		var datelabel = $('label[for=' + 'date'+idx + ']');
		var timelabel = $('label[for=' + 'time'+idx + ']');
		var date = new Date(datefield.val());
		var days = $('#pcc-day').val().split(',');
		var day = date.getDay();
		if (date.getTime() <= enddate.getTime()){
			datefield.add(datelabel).removeClass('in-error');
		}
		else {
			datefield.add(datelabel).addClass('in-error');
			msg = "Please choose an earlier date, the Preventive Care Clinic ends on "+str+".<br />";
		}
		if (msg == '') {
			var success = false;
			for (i = 0; i < days.length; i++) {
				if (day == days[i]) {
					success = true;
				}
			}
			if (success) {
				datefield.add(datelabel).removeClass('in-error');
			}
			else {
				datefield.add(datelabel).addClass('in-error');
				msg = "Please choose a day when the Preventive Care Clinic is offered.<br />";
			}
		}
		
		
		if (msg == '' && timefield.val() != '') {
			var success = false;
			var froms = $('#pcc-from').val().split(',');
			var tos = $('#pcc-to').val().split(',');
			var time = Number(timefield.val().replace(/:/g, '.'));
			if ($('#am' + idx).is(':checked') && Math.floor(time) == 12) {
				time = time - 12;
			}
			if ($('#pm' + idx).is(':checked') && Math.floor(time) != 12) {
				time = time + 12;
			}
			for (i = 0; i < days.length; i++) {
				if (day == days[i]) {
					if (time >= Number(froms[i]) && time <= Number(tos[i])) {
						success = true;
					}
				}
			}
			if (success) {
				timefield.add(timelabel).removeClass('in-error');
			}
			else {
				timefield.add(timelabel).addClass('in-error');
				msg = "Please choose a time during Preventive Care Clinic hours.<br />";
			}
		}
	}
	return msg;
}

function trimInput(){
	$(':input[type=text], textarea').each(function(){
		var val = $(this).val().replace(/^\s+|\s+$/, ''); // trim leading/trailing whitespace
		$(this).val(val);
	});
}

function cleanInput(){
	$(':input[type=text], textarea').each(function(){
		var val = $(this).val()
			.replace(/"/g, '&#34;') // replace " with entity
			.replace(/'/g, '&#39;') // replace ' with entitiy
			.replace(new RegExp('/', 'g'), '&#47;') // replace / with entity
			.replace(/_/g, '&#95;') // replace _ with entity
			.replace(/%/g, '&#37;'); // replace % with entity
		$(this).val(val);
	});
}

var rx = {
	name: /^[\-A-Z',\.\s]*$/i, // matches name: letters, dash, period, comma, apostrophe [\w -.,']
	addr: /^[\-\w0-9:\,#\.\/\s]*$/, // matches address: letters, numbers, dash, period, comma, slash, colon, hash [\w\d -.,/:#]
	zip: /^\d{5}([\-\s]?\d{4})?$/, // matches zip code: ##### or #####-#### or ##### ####
	phone: /^\(?\d{3}\)?[\.\s\-]?\d{3}[\.\s\-]?\d{4}$/, // matches phone number: ###-###-#### or (###) ###-#### or ### ### #### or ###.###.#####
	email: /^[A-Z0-9._+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, // matches email: xx@xx.xxx
	date: /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)\d\d$/, // matches date: dd/mm/yyyy
	trim: /^\s+|\s+$/, // matches leading or trailing whitespace (space, tab, line break)
	tag: /<([A-Z][A-Z0-9]*)\b[^>]*>(.*?)<\/\1>/i, // matches html tag, return content inside tag
	date: /^(0[1-9]|1[012])[-\s\/\.](0[1-9]|[12][0-9]|3[01])[-\s\/\.](19|20)\d\d$/, // matches date: MM-DD-YYYY or MM.DD.YYYY or MM/DD/YYYY or MM DD YYYY
	time: /^(1[0-2]|0?[1-9])(:[0-5][0-9])*$/,
	money: /^\$?([0-9]+(,[0-9]{3})*(\.[0-9]{2})?)?$/
};


