
String.prototype.trim = function() {
	return this.replace(/^\s*(.*?)\s*$/, '$1');
};

String.prototype.isEmail = function() {
	var emailReg = /^[a-zA-Z_0-9\.\-]+\@([a-zA-Z_0-9\-]+\.)+[a-zA-Z_0-9\-]+$/;
	return emailReg.test(this.trim());
};

String.prototype.isVBPassword = function() {
	var regex = /^[a-zA-Z0-9]{5,10}$/;
	return regex.test(this.trim());
};

/* Check for blank */
function IsBlank(value) {
	return ! (/\S/).test(value);
}

/* Validate that a value is a non-negative integer. Cannot be blank. DOES allow leading zeros.
 * Returns true if the value (as a stripped string) only contains digits 0-9, else returns false.
 */
function IsInteger(value)
{
	var regex = /^\d+$/;
	return regex.test(value.trim());
}

function DoFail(ctl, msg) {
	ctl.focus();
	alert(msg);
	return false;
}

function popup(mylink, windowname, width, height, scrollbars) {
	if (! window.focus) return;
	var href;
	if (typeof(mylink) == 'string') href=mylink;
	else href=mylink.href;
	window.open(href, windowname, 'width=' + width + ',height=' + height + ',scrollbars=' + scrollbars);
	return false;
}

//////

function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function changeImages(imgID, src) {
	if (!document.getElementById) return;
	var img = document.getElementById(imgID);
	if (!img) return;
	img.src = src;
}

function changeLink(linkID, url) {
	if (!document.getElementById) return;
	var link = document.getElementById(linkID);
	if (!link) return;
	link.href = url;
}

//////

function submitQuickSearch(){
	var frm = document.getElementById('quickSearchForm');

	if (validateQuickSearch(frm))
		frm.submit();
}

function validateQuickSearch(frm){
	
	if(!frm)
		return false;

	if( frm.sTitle.value.trim()=='' && frm.sAuthor.value.trim()=='' && frm.sKeyword.value.trim()=='' && frm.sISBN.value.trim()=='')
		return DoFail(frm.sTitle, 'Please enter search information.');

	return true;
}

// validate login form
var alreadySubmitted = false; 
function dtsCanLogIn(frm) {
	if (alreadySubmitted) {
		alert("Please wait while we gather your information.");
		return false;
	}
	var s = frm.email.value.trim();
	if (s == '')
		return DoFail(frm.email, "You must enter your Username.");
	if (!s.isEmail())
		return DoFail(frm.email, "Your Username must be a valid email address.");
	s = frm.password.value.trim();
	if (s == '')
		return DoFail(frm.password, "You must enter your Password.");
	if (!s.isVBPassword())
		return DoFail(frm.password, "Your Password must be between 5 and 10 alphanumeric characters.\n"
			+ "Please do not use spaces or punctuation - just letters and/or numbers.");
	alreadySubmitted = true;
	return true;
}

// helper for detail page
var currTab = new Array();
function setCntTab(tabId, sectId) {
	document.getElementById('cntTb' + sectId + '_' + currTab[sectId]).className	= 'contentTabOff';
	document.getElementById('cntStr' + sectId + '_' + currTab[sectId]).className	= 'hid';
	document.getElementById('cntTb' + sectId + '_' + tabId).className		= 'contentTabOn';
	document.getElementById('cntStr' + sectId + '_' + tabId).className		= 'vis2';
	currTab[sectId]	= tabId;
}

//////

// validate card verify form
function ValidateVerifyForm(frm){

	if (IsBlank(frm.fvCardNumber.value))
		return DoFail(frm.fvCardNumber,"Enter a card number.");

	if (!CardNumberCheck(frm.fvCardNumber))
		return DoFail(frm.fvCardNumber,"Invalid card number");

	return true;
}

// check ebook card number
function CardNumberCheck(CardNumber)
{
	if (!IsBlank(CardNumber.value))
	{
		if (CardNumber.value.length != 16)  return false;
		else if (!IsInteger(CardNumber.value))  return false;
		else
		{
			sum = 0;
			value = CardNumber.value;
			i = value.length-1;
			even = true;
			while (i >= 0) {
				ch = value.charAt(i);
				digit = parseInt(ch);
				if (!even) {
					digit *= 2;
					if (digit > 9)	digit -= 9;
				}
				sum += digit;
				even = !even;
				--i;
			}
			if((sum % 10) != 0)
				return false;
		}
	}

	return true;
}

// check terms and conditions
function CheckTermsAccept(frm)
{

	if (frm.fvAcceptRequirements.type == 'checkbox' && !frm.fvAcceptRequirements.checked)
		return DoFail(frm.fvAcceptRequirements,"You must accept all terms and conditions to continue to card activation.");
	if (!frm.fvAcceptRestrictions.checked)
		return DoFail(frm.fvAcceptRestrictions,"You must accept all terms and conditions to continue to card activation.");
	if (!frm.fvAcceptReceipt.checked)
		return DoFail(frm.fvAcceptReceipt,"You must accept all terms and conditions to continue to card activation.");
}

//////

// validate code form
function ValidateCodeForm(frm){

	// Validate Visual Verify number
	if (IsBlank(frm.fvVisualVerify.value))
		return DoFail(frm.fvVisualVerify,"Enter the number in the image.");

	// Validate Receipt/Transaction Code
	var ReceiptCode = frm.fvReceiptCode.value.trim();
	if (ReceiptCode == '')
		return DoFail(frm.fvReceiptCode,"Enter the Receipt Code.");
	ReceiptCode = ReceiptCode.replace(/\s+/g, '');
	if (ReceiptCode.length != 12)
		return DoFail(frm.fvReceiptCode,"Enter a valid Receipt Code.");

	// Validate Activation Code
	var fvScratchNumber = frm.fvScratchNumber.value.trim();
	if (fvScratchNumber == '')
		return DoFail(frm.fvScratchNumber,"Enter the Activation Code.");
	if (!ScratchNumberCheck(frm.fvScratchNumber))
		return DoFail(frm.fvScratchNumber,"Enter a valid Activation Code.");

	hideProcessSubmit(frm, 'activateCodeSubmitButton', 'activateCodeSubmitLoading');

	// always return false, hideSubmitBlock() will submit the form
	return false;
}

// validate card scratch/private numbers
function ScratchNumberCheck(ScratchNumber)
{
	if (IsBlank(ScratchNumber.value))  return false;
	else if (ScratchNumber.value.length != 10)  return false;

	return true;
}

// hide button, show processing image, then submit form
function hideProcessSubmit(frm, hideID, showID) {
	if (!frm || document.getElementById(hideID).className != 'vis')
		return false;

	// setup action for timeout call
	var action = 'document.' + frm.name + '.submit()';

	document.getElementById(hideID).className	= 'hid';
	document.getElementById(showID).className	= 'vis';
	setTimeout(action,250);

	return true;
}

/**************************************************************************************************/

var expandedText = new Array();

function ManualShrinkText(id, cutoff) {
	if (!document.getElementById)
		return false;

	var el = document.getElementById(id);
	if (!el)
		return false;

	/* Hide the div so it is not visibly twitching on the screen */
	el.visibility = "hidden";

	/* Our data will be appended to expandedText[], so the index to our data
	 * is the current length of expandedText[] */
	var ofs = expandedText.length;

	/* Get original text */
	var orig = el.innerHTML.trim();

	/* Append a "... click to collapse" element */
	var expanded = orig + '<a class="manualExpandor" href="javascript:ShrinkText(' + ofs + ')">... click to collapse \xab</a>';

	/* Append a "... click to expand" element */
	var shrunk = orig.substr(0, cutoff) + '<a class="manualExpandor" href="javascript:ExpandText(' + ofs + ')">... click to expand \xbb</a>';

	/* Save shrink info */
	expandedText[ofs] = new Array(el, expanded, shrunk);
	el.innerHTML = shrunk;

	el.visibility = "visible";
}

function ExpandText(idx) {
	if (idx >= 0 && expandedText[idx] && expandedText[idx][0] && expandedText[idx][1]) {
		var el = expandedText[idx][0];
		var markup = expandedText[idx][1];
		el.innerHTML = markup;
	}
}

function ShrinkText(idx) {
	if (idx >= 0 && expandedText[idx] && expandedText[idx][0] && expandedText[idx][2]) {
		var el = expandedText[idx][0];
		var markup = expandedText[idx][2];
		el.innerHTML = markup;
	}
}
