var coupon_tmr_handle = '';
var coupon_tmr_code = '';
var coupon_animating = false;

// Change the background color of the password_verify boxes if the passwords
// do not match. More could be done (ie. minimum length) but this should be
// good for now.
function verifypassword() {
	var x, elem2, elem = $(':input[id^=password\:]');

	for (x = 0; x < elem.length; x++) {
		elem2 = $('#password_verify'+elem[x].name.substr(8).replace(/:/g, '\\:'));

		if (elem2.length) {
			if (elem2[0].value != elem[x].value) {
				elem2.css('background', '#ffcccc');
				elem2.css('color', '#000000');
			} else {
				elem2.css('background', elem.css('background'));
				elem2.css('color', elem.css('color'));
			}
		}
	}

	return;
}

// Prevent certain keys from being used in certain text boxes
function restrict(e, values) {
	var val;

	if (typeof(e.which) != 'undefined') {
		val = e.which;
	} else {
		val = e.keyCode;
	}

	// Return true for navigation keys, backspace, enter
	if ((val == 0) || (val == 8) || (val == 13)) {
		return true;
	}

	// Or if the user typed an allowed character...
	if (values.indexOf(String.fromCharCode(val)) != -1) {
		return true;
	}

	return false;
}

function phoneonly(e) {
	// Some people use parens and dashes while others use periods
	// to delineate their phone numbers.
	return restrict(e, '0123456789()-.');
}

function numericonly(e) {
	return restrict(e, '0123456789');
}

// For the PayPal/Credit Card radio buttons
function showhide_cc(show, low, high) {
	if (low === undefined) {
		low = 1;
	}
	if (high === undefined) {
		high = 0;
	}
	for (var x = low; elem = document.getElementById('cc_'+x); x++) {
		if (show)
			elem.style.display = '';
		else
			elem.style.display = 'none';

		if (x == high)
			break;
	}
}

// Show or hide altcity, based on the selection of city
function showhide_city() {
	var elem2, elem1 = $(':input[id^=city\:]')[0];

	if (elem1 != null) {
		id = elem1.name.substr(4).replace(/:/g, '\\:');
		elem2 = $('#hiddencity'+id);

		if (elem1.options[elem1.selectedIndex].text == 'Other') {
			elem2.show();
		} else {
			elem2.hide();
		}

		elem1 = $('#altcity'+id);
		if (elem1 != null) {
			elem1.focus();
		}
	}
}

function NewWindow(mypage, myname, w, h, scroll, pos, return_handle) {
	var settings, url, handle, l = 0, t = 20;

	/* Default parameters, where unspecified */
	if (myname == undefined) {
		myname = 'childwin';
	}
	if (w == undefined) {
		w = screen.width * 3 / 4;
	}
	if (h == undefined) {
		h = screen.height * 3 / 4;
	}
	if (scroll == undefined) {
		scroll = 'yes';
	}

	/* Calculate where to place our new window */
	if ((pos == undefined) || (pos == 'center')) {
		l = (screen.width) ? (screen.width - w) / 2 : 100;
		t = (screen.height) ? (screen.height - h) / 2 : 100;
	} else if (pos == "random") {
		l = (screen.width) ? Math.floor(Math.random() * (screen.width - w)) : 100;
		t = (screen.height) ? Math.floor(Math.random() * ((screen.height - h) - 75)) : 100;
	}

	/* JS window configuration string */
	settings  = 'width='+w+',height='+h+',top='+t+',left='+l+',scrollbars='+scroll;
	settings += ',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';

	/* Append 'popup=true' to the query string for the URL */
	url  = mypage + ((mypage.indexOf('?') == -1) ? '?' : '&');
	url += 'popup=true';

	/* Open the window, then decide if we should return a handle to it (useful for
	 * <a href="blah.html" onclick="return NewWindow(this.href)">link</a>) */
	handle = window.open(url, myname, settings);
	if (window.focus) {
		handle.focus();
	}

	return ((return_handle != undefined) && return_handle) ? handle : false;
}

function form_value(id, value, submit) {
	var elem = $('#'+id);

	elem[0].value = value;
	if ((submit != undefined) && submit) {
		elem.parents('form:first').submit();
	}
}

function discount_days(total, coupon_amount, coupon_type) {
	// Pull the value from controls with ids that begin with coupon_amount
	// and coupon_type if we were not passed specific values already.
	if (coupon_amount == undefined) {
		coupon_amount = new Number($('input[id^=coupon_amount]')[0].value);
	}
	if (coupon_type == undefined) {
		coupon_type = $('input[id^=coupon_type]')[0].value;
	}

	// Apply a discount, if any
	value = '';
	if ((coupon_type == 'day') || (coupon_type == 'week')) {
		if (coupon_amount < 1) {
			coupon_amount = 1;
		}
		value = parseInt(coupon_amount)+' '+coupon_type+((coupon_amount > 1) ? 's' : '');
	}

	return value;
}

function discount_amount(total, coupon_amount, coupon_type, quantity) {
	// Pull the value from controls with ids that begin with coupon_amount
	// and coupon_type if we were not passed specific values already.
	if (coupon_amount == undefined) {
		coupon_amount = new Number($('input[id^=coupon_amount]')[0].value);
	}
	if (coupon_type == undefined) {
		coupon_type = $('input[id^=coupon_type]')[0].value;
	}

	// Apply a discount, if any
	value = '';
	if ((coupon_type != 'day') && (coupon_type != 'week')) {
		if ((coupon_amount != '') && (coupon_amount != 0)) {
			// Support percentages, in addition to dollar amounts...
			value = coupon_amount;
			if (coupon_type == 'percent') {
				value = total * (coupon_amount / 100);
			} else if (quantity != undefined) {
				value *= quantity;
			}

			// ensure that we don not create a negative number
			if (value > total) {
				value = total;
			}
		}
	}

	return value;
}

function coupon_ajax_error(XMLHttpRequest, textStatus, errorThrown) {
	$('img[id^=coupon_stat]')[0].src = '/images/errcircle.gif';
	coupon_animating = false;

	return;
}

function coupon_ajax_success(data, textStatus) {
	var coupon_amount = '', coupon_type = '', d = data.split('"');

	if ((data != '0') && ($('input[id^=coupon_code]')[0].value == d[0])) {
		$('img[id^=coupon_stat]')[0].src = '/images/statcircle.gif';

		coupon_amount = d[1];
		coupon_type = d[2];
	} else {
		$('img[id^=coupon_stat]')[0].src = '/images/errcircle.gif';
	}

	$('input[id^=coupon_amount]')[0].value = coupon_amount;
	$('input[id^=coupon_type]')[0].value = coupon_type;
	coupon_animating = false;
	update_total();

	return;
}

function coupon_verify() {
	var send, member, user_id;

	// Stop the timer.
	window.clearInterval(coupon_tmr_handle);

	// Make sure we do have data, and then request coupon
	// information from the server.
	if (coupon_tmr_code) {
		// Try to load from a member selection drop-down (administrative, but we guard
		// against abuse in the server code).
		member = $(':input[id^=member\:]');
		user_id = member.length ? member[0].options[member[0].selectedIndex].value : 0;

		// Or the current user's ID (again, protected in the server-side code).
		if (!user_id) {
			member = $(':input[id^=id\:]');
			user_id = member.length ? member[0].value : 0;
		}

		$.ajax({
			url: "/coupon.php",
			type: "POST",
			data: ({code: coupon_tmr_code, uid: user_id}),
			dataType: 'text',
			error: coupon_ajax_error,
			success: coupon_ajax_success
		});
	}

	return;
}

function coupon_queue() {
	var val = $('input[id^=coupon_code]')[0].value;

	if (coupon_tmr_code == val) {
		return;
	}

	// Cancel the timer, if any
	if (coupon_tmr_handle) {
		window.clearInterval(coupon_tmr_handle);
	}

	// Hide our success/error messages
	control = $('#coupon_error');
	control.stop();
	control.hide('fast');

	control = $('#coupon_success');
	control.stop();
	control.hide('fast');

	// Animate the circle...
	if (val) {
		if (!coupon_animating) {
			$('img[id^=coupon_stat]')[0].src = '/images/anicircle.gif';
		coupon_animating = true;
		}

		// Go ahead and clear the coupon information...
		$('input[id^=coupon_amount]')[0].value = '';
		$('input[id^=coupon_type]')[0].value = '';

		coupon_tmr_code = val;

		// Check the coupon one second from now, if we don't cancel
		// it before with a subsequent call to this function.
		coupon_tmr_handle = window.setInterval('coupon_verify()', 1000);
	} else {
		// No coupon; stop the animation.
		coupon_tmr_handle = '';
		coupon_tmr_code = '';
		$('input[id^=coupon_amount]')[0].value = '';
		$('input[id^=coupon_type]')[0].value = '';

		$('img[id^=coupon_stat]')[0].src = '/images/statcircle.gif';
		coupon_animating = false;

		// Calculate the proper amount (user function).
		update_total();
	}

	return;
}

