function trim(s) {

    if((s==null)||(typeof(s)!='string')||!s.length) {
        return '';
    }
    return s.replace(/^\s+/,'').replace(/\s+$/,'');

}

function check_blank(field) {

    if (field == '') {
        return false;
    }
    if (trim(field) == '') {
        return false;
    }
    return true;
}

function isDigit(num) {
    
    if (num.length>1) { 
        return false;
    }
    var string="1234567890";
    if (string.indexOf(num)!=-1) { 
        return true;
    }
    return false;
}

function isInteger(val){
    
    for(var i=0;i<val.length;i++) {
	if(!isDigit(val.charAt(i))) {
	    return false;
	}
    }
    return true;
}

function isExpiryDate(year, month) {

    var today = new Date();
    var expiry = new Date(year, month);

    if (today.getTime() > expiry.getTime()) {
    	return true;
    }
    
    else {
	return false;
    }
}

function testCreditCard (ccnum, cctype, ccexpirymonth, ccexpiryyear, cid) {

  if (!check_blank(cid)) {
      return "ccid_blank"; 
  }
  else if (!isInteger(cid)) {
      return "ccid_number";
  }
  else if ((cid.length < 3) || (cid.length > 4)) {
      return "ccid_length";
  }
  else if (isExpiryDate(ccexpiryyear, ccexpirymonth)) {
      return "expired";
  }
  else if (checkCreditCard (ccnum, cctype)) {
      return "valid";
  } 
  else {
      return "invalid";
  }
}

function validate_area(area) {

    if ((area.length == 3) && (isInteger(area))) {
	return true;
    }
    else {
	return false;
    }
}

function validate_phone(phone) {

    var regex  = /^\d{3}\-\d{4}$/;

    return regex.test(phone);
}

function echeck(str) {

      var at="@";
      var dot=".";
      var lat=str.indexOf(at);
      var lstr=str.length;
      var ldot=str.indexOf(dot);

      if (str.indexOf(at)==-1){
	   return false;
      }

      if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
          return false;
      }

      if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
 	  return false;
      }

      if (str.indexOf(at,(lat+1))!=-1){
	  return false;
      }

      if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	  return false;
      }

      if (str.indexOf(dot,(lat+2))==-1){
          return false;
      }
		
      if (str.indexOf(" ")!=-1){
	  return false;
      }

      return true;					
}

function validate_amount(amount) {
    
    var regex = /^([0-9]+)(.[0-9][0-9])?$/; 
    return regex.test(amount);
}

function validate_date(dateValue) {
    
    var regex = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)[0-9]{2}$/;
    return regex.test(dateValue);
}

function validate_postal(postal) {

    var regex = /^\D{1}\d{1}\D{1}\ \d{1}\D{1}\d{1}$/;
    return regex.test(postal);
}

function validate_login() {
    
    var userName = document.form1.username.value;
    var password = document.form1.password.value;

    if (!check_blank(userName)) {
	alert("User Name cannot be blank.");
	return false;
    }

    if (!check_blank(password)) {
	alert("Password cannot be blank.");
	return false;
    }

    return true;
}

function validate_startDate(startDate) {

    var today = new Date();
    var temp = startDate.split('/');
    var day = temp[0];
    var month = temp[1]-1;
    var year = temp[2];
    var sDate = new Date(year, month, day);

    if (today.getTime() <= sDate.getTime()) {
    	return true;
    }
    
    else {
	return false;
    }
}

function validate_dates(startDate, endDate) {

    var temp = startDate.split('/');
    var day = temp[0];
    var month = temp[1];
    var year = temp[2];
    var sDate = new Date(year, month, day); 
    temp = endDate.split('/');
    day = temp[0];
    month = temp[1];
    year = temp[2];
    var eDate = new Date(year, month, day);

    if (sDate.getTime() >= eDate.getTime()) {
	return false;
    }

    else {
	return true;
    }
}

function validate_step2() {

    var amount = document.form1.amount.value;
    var frequency = document.form1.frequency;
    var startDate = document.form1.startDate.value;
    var endDate = document.form1.endDate.value;
    var instructions = document.form1.instructions.value;
    var dedication = document.form1.dedication.value;
    var memoryOf = document.form1.memoryOf.value;
    var honourOf = document.form1.honourOf.value;
    var isCC = document.form1.isCC.value;
    var ccnum = document.form1.ccnum.value;
    var ccname = document.form1.ccname.value;
    var cctype = document.form1.cctype.value;
    var ccmon = document.form1.ccmon.value;
    var ccyear = document.form1.ccyear.value;
    var cid = document.form1.cid.value;

    if (!check_blank(amount)) {
	alert("Donation amount is required.");
	return false;
    }
	
    if (amount <= 0) {
	alert("Amount must be more than 0.");
	return false;
    }

    if (!validate_amount(amount)) {
	alert("Donation amount invalid. It must appear in the form XX.XX or XXXX (ie. 20.00 or 1000.00).")
	return false;
    }

    if (!frequency[0].checked && !frequency[1].checked) {
	alert("You must choose a Donation Frequency.");
	return false;
    }

    if (document.getElementById('freqRepeat').checked) {
	if (!check_blank(startDate)) {
	    alert("Start Date is required if you choose to make a repeating donation.");
	    return false;
	}
	else if (!validate_date(startDate)) {
	    alert("Your Start Date is invalid. It must appear in the form dd/mm/yyyy.");
	    return false;
	}
	else if (!validate_startDate(startDate)) {
	    alert("You cannot specify a Start Date in the past.");
	    return false;
	}
	if (!check_blank(endDate)) {
	    alert("End Date is required if you choose to make a repeating donation.");
	    return false;
	}
	if (!validate_date(endDate)) {
	        alert("Your End Date is invalid. If you choose an End Date for your repeating donation, it must appear in the form dd/mm/yyyy.");
		return false;
	}
	if (!validate_dates(startDate, endDate)) {
		alert("You must specify an End Date later than your Start Date.");
		return false;
	}
    }

    if (document.getElementById('dedMemory').checked) {
	if (!check_blank(memoryOf)) {
	    alert("In Memory of cannot be blank if you select a dedication.");
	    return false;
	}
    }

    if (document.getElementById('dedHonour').checked) {
	if (!check_blank(honourOf)) {
	    alert("In honour of/on behalf of cannot be blank if you select a dedication.");
	    return false;
	}
    }
  
  if (isCC == "yes") {
    if (!check_blank(ccname)) {
	alert ("Your card holder name is required.");
	return false;
    }

    if (!check_blank(ccnum)) {
	alert ("Your credit card number is required.");
	return false;
    }

    if (cctype == "0") {
	alert ("You must select a credit card type.");
	return false;
    }

    if (ccmon == "0") {
	alert ("You must select a credit card expiry month.");
	return false;
    }

    if (ccyear == "0") {
	alert ("You must select a credit card expiry year.");
	return false;
    }

	var valid = testCreditCard(ccnum, cctype, ccmon, ccyear, cid);
	if (valid == "ccid_blank") {
	    alert("CCID cannot be blank");
	    return false;
	}
	else if (valid == "ccid_number") {
	    alert("CCID must only contain numbers");
	    return false;
	}
	else if (valid == "ccid_length") {
	    alert("CCID must be 3 or 4 digits.");
	    return false;
	}
	else if (valid == "expired") {
	    alert ("Your credit card is expired.");
	    return false;
	}
	else if (valid == "invalid") {
	    alert ("Invalid credit card number for " + cctype);
	    return false;
	}
	else if (valid == "valid") {
	    return true;
	}
	else {
	    alert ("Unknown error validating credit card number.");
	    return false;
	}
  }
  return true;
}

function validate_step2Batch() {
    
    var amount = document.form1.amount.value;
    var frequency = document.form1.frequency;
    var startDate = document.form1.startDate.value;
    var endDate = document.form1.endDate.value;
    var paymentType = document.form1.paymentType;
    var batchMethod = document.form1.batchMethod.value;

    if (!check_blank(amount)) {
	alert("Donation amount is required.");
	return false;
    }
	
    if (amount <= 0) {
	alert("Amount must be more than 0.");
	return false;
    }

    if (!validate_amount(amount)) {
	alert("Donation amount invalid. It must appear in the form XX.XX or XXXX (ie. 20.00 or 1000.00).")
	return false;
    }

    if (!frequency[0].checked && !frequency[1].checked) {
	alert("You must choose a Donation Frequency.");
	return false;
    }

    if (document.getElementById('freqRepeat').checked) {
	if (!check_blank(startDate)) {
	    alert("Start Date is required if you choose to make a repeating donation.");
	    return false;
	}
	else if (!validate_date(startDate)) {
	    alert("Your Start Date is invalid. It must appear in the form dd/mm/yyyy.");
	    return false;
	}
	else if (!validate_startDate(startDate)) {
	    alert("You cannot specify a Start Date in the past.");
	    return false;
	}
	if (!check_blank(endDate)) {
	    alert("End Date is required if you choose to make a repeating donation.");
	    return false
  	}
	if (!validate_date(endDate)) {
	    alert("Your End Date is invalid. If you choose an End Date for your repeating donation, it must appear in the form dd/mm/yyyy.");
	    return false;
	}
	if (!validate_dates(startDate, endDate)) {
	    alert("You must specify an End Date later than your Start Date.");
	    return false;
	}
    }
    
    if (!paymentType[0].checked && !paymentType[1].checked && !paymentType[2].checked && !paymentType[3].checked && !paymentType[4].checked) {
	alert("You must choose a payment method");
	return false;
    }

    if (batchMethod == "Manual") {
	var receiptNumber = document.form1.receiptNumber.value;
	var receiptDate = document.form1.receiptDate.value;
	if (!check_blank(receiptNumber)) {
	    alert("You must provide a Receipt Number if you choose the Receipt Batch Method.");
	    return false;
	}
	if (!check_blank(receiptDate)) {
	    alert("You must provide a Receipt Date if you choose the Receipt Batch Method.");
	    return false;
	}
	if (!validate_date(receiptDate)) {
	    alert("Your Receipt Date is invalid. It must appear in the form dd/mm/yyyy.");
	    return false;
	}
    }

    return true;
}

function validate_step1(emailRequired) {

    var prefix = document.form1.prefix.value;
    var firstname = document.form1.firstname.value;
    var lastname = document.form1.lastname.value;
    var organization = document.form1.organization.value;
    var contact = document.form1.contact.value;
    var addressTwo = document.form1.addressTwo.value;
    var city = document.form1.city.value;
    var province = document.form1.province.value;
    var postal = document.form1.postal.value;
    var phone = document.form1.phone.value;
    var email = document.form1.email.value;
    var isBatch = document.form1.isBatch.value;
    
    if (isBatch == 'Yes') {
	var batchMethod = document.form1.batchMethod;
	if (batchMethod[0] && batchMethod[1] && batchMethod[2]) {
	    if (!batchMethod[0].checked && !batchMethod[1].checked && !batchMethod[2].checked) {
	        alert("You must choose a Batch Method or indicate this is a Private Sponsor.");
	        return false;
	    }
	}
	else {
	    batchMethod = batchMethod.value;
	    if(!check_blank(batchMethod)) {
		alert("You must choose a Batch Method");
		return false;
	    }
	}
    }

    if (!check_blank(prefix)) {
	alert("You must specify a Prefix.");
	return false;
    }
    
    if ((!check_blank(firstname) || !check_blank(lastname)) && !check_blank(organization)) {
	alert ("You must provide either your First Name and Last Name, or the name of your organization.");
	return false;
    }

    if (check_blank(organization)) { //must have something for contact name
	if (!check_blank(contact)) {
	    if (check_blank(firstname)) {
		alert("You must provide a Contact Name if indicate you are an organization. Please just use what you have typed in the First Name and Last Name fields and place them in the Contact Name field instead.");
		return false;
	    }
	    else {
	        alert("You must provide a Contact Name if indicate you are an organization.");
	    }
	    return false;
	}
    }

    if (check_blank(organization) && check_blank(firstname) && check_blank(lastname) && check_blank(contact)) {
	alert("Please do not fill in the First Name and Last Name fields if you are an organization. Use the Contact Name field instead to indicate your full name. If you are an individual, please do not use the Organization or Contact Name fields.");
	return false;
    }

    if (!check_blank(addressTwo)) {
	alert("Address is required.");
	return false;
    }

    if (!check_blank(city)) {
	alert("City is required.");
	return false;
    }

    if (!check_blank(province)) {
	alert("Province is required.");
	return false;
    }

    if (!check_blank(postal)) {
	alert("Postal Code is required.");
	return false;
    }

    if(!validate_postal(postal)) {
	alert("Postal Code is invalid. It must appear in the form T2A 2T3 (with a space).");
	return false;
    }

    if (!check_blank(phone) && !check_blank(email)) {
	alert("You must provide at least one of Phone and Email.");
	return false;
    }

    if (emailRequired && !check_blank(email)) {
	alert("Your email address is required.");
	return false;
    }
    
    if (check_blank(email) && !echeck(email)) {
	alert("Email is invalid.");
	return false;
    }

    return true;
}

function validate_search() {
    
    var ds = document.form1.datestart.value;
    var de = document.form1.dateend.value;
    var postal = document.form1.postal.value;

    if (check_blank(ds) && !validate_date(ds)) {
	alert('Invalid starting date format');
	return false;
    }

    if (check_blank(de) && !validate_date(de)) {
	alert('Invalid ending date format');
	return false;
    }

    if (check_blank(postal) && !validate_postal(postal)) {
   	alert('Invalid Postal Code');
	return false;
    }

    return true;
}

function validateDonor_search() {
    
    var postal = document.form1.postal.value;

    if (check_blank(postal) && !validate_postal(postal)) {
   	alert('Invalid Postal Code');
	return false;
    }

    return true;
}

function validateDonor_update(form) {
    
    var addressTwo = form.addressTwo.value;
    var city = form.city.value;
    var province = form.province.value;
    var postal = form.postal.value;
    var phone = form.phonehome.value;
    var email = form.email.value;

    if (!check_blank(addressTwo)) {
	alert("Address is required.");
	return false;
    }

    if (!check_blank(city)) {
	alert("City is required.");
	return false;
    }

    if (!check_blank(province)) {
	alert("Province is required.");
	return false;
    }

    if (!check_blank(postal)) {
	alert("Postal Code is required.");
	return false;
    }

    if(!validate_postal(postal)) {
	alert("Postal Code is invalid. It must appear in the form T2A 2T3.");
	return false;
    }

    if (!check_blank(phone) && !check_blank(email)) {
	alert("You must provide at least one of Phone and Email.");
	return false;
    }

    if (check_blank(email) && !echeck(email)) {
	alert("Email is invalid.");
	return false;
    }

    return true;
}

function validate_clerk(userName, password, firstname, lastname) {

    if (!check_blank(userName)) {
	alert('User Name cannot be blank');
	return false;
    }

    if (!check_blank(password)) {
	alert('Password cannot be blank');
	return false;
    }

    if (!check_blank(firstname)) {
	alert('First Name cannot be blank');
	return false;
    }

    if (!check_blank(lastname)) {
	alert('Last Name cannot be blank');
	return false;
    }

    return true;
}

function validate_volunteer() {
    
    var name = document.form1.name.value;
    var addressOne = document.form1.addressOne.value;
    var city = document.form1.city.value;
    var province = document.form1.province.value;
    var postal = document.form1.postal.value;
    var phone = document.form1.phone.value;
    var email = document.form1.email.value;
    var preference = document.form1.preference.value;
    var agree = document.form1.agree;

    if (!check_blank(name)) {
        alert("Contact Name is required.");
	return false;
    }

    if (!check_blank(addressOne)) {
	alert("Address is required.");
	return false;
    }

    if (!check_blank(city)) {
	alert("City is required.");
	return false;
    }

    if (!check_blank(province)) {
	alert("Province is required.");
	return false;
    }

    if (check_blank(postal) && !validate_postal(postal)) {
   	alert('Invalid Postal Code');
	return false;
    }

    if (!check_blank(phone)) {
	alert("You must provide your Phone Number.");
	return false;
    }

    if(check_blank(email) && !echeck(email)) {
	alert("Invalid email address");
	return false;
    }

    if (!check_blank(preference)) {
	alert("You must indicate what your volunteer preference is.");
	return false;
    }

    if (!agree.checked) {
	alert('You must agree to the Oath of Confidentiality by checking the box beside "I Agree"');
	return false;
    }

    return true;
}

function validateBatch_search() {
    
    var sd = document.formBatch.startDate.value;
    var ed = document.formBatch.endDate.value;

    if (check_blank(sd) && !validate_date(sd)) {
	alert('Invalid Start Date format');
	return false;
    }
    
    if (check_blank(ed) && !validate_date(ed)) {
	alert('Invalid End Date format');
	return false;
    }

    return true;
}

function validate_years() {
    
    var regex  = /^\d{4}((,\d{4})*)$/;
    var years = document.csvForm.years.value;

    if (!check_blank(years)) {
	alert("Input cannot be blank");
	return false;
    }
    else if (regex.test(years)) {
	return true;
    }
    else {
	alert("Input must be a list of years separated by commas and no spaces.\n\ni.e. 2008,2007\ni.e. 2008");
	return false;
    }
}

function validate_merge() {
    
    var mergeOne = document.mergeForm.mergeOne.value;
    var mergeTwo = document.mergeForm.mergeTwo.value;

    if (!check_blank(mergeOne)) {
	alert('You must provide two Donor Ids to merge.');
	return false;
    }

    if (!check_blank(mergeTwo)) {
	alert('You must provide two Donor Ids to merge.');
	return false;
    }

    if (!isInteger(mergeOne)) {
	alert('Donor IDs must be numbers.');
	return false;
    }

    if (!isInteger(mergeTwo)) {
	alert('Donor IDs must be numbers.');
	return false;
    }

    return true;
}

function confirm_merge() {
    
    var mergeOne = document.mergeForm.mergeOne.value;
    var mergeTwo = document.mergeForm.mergeTwo.value;

    var mergeString = getMergeString(mergeOne, mergeTwo);

    return confirm('Are you sure you want to merge the selected donors? Note the oldest information will take precedence.\n\n' + mergeString);
}

function validateVolunteerPosition(title, description) {
    
    if (!check_blank(title)) {
	alert('You must provide a title');
	return false;
    }

    if (!check_blank(description)) {
	alert('You must provide a description');
	return false;
    }
}

function validateGroupVolunteerPosition(title, description) {
    
    if (!check_blank(title)) {
	alert('You must provide a title');
	return false;
    }

    if (!check_blank(description)) {
	alert('You must provide a description');
	return false;
    }
}

function validateEmploymentPosition(title, description) {
    
    if (!check_blank(title)) {
	alert('You must provide a title');
	return false;
    }

    if (!check_blank(description)) {
	alert('You must provide a description');
	return false;
    }
}

function validateEvent(startDate, endDate, title, description) {
   
    if (!check_blank(startDate)) {
	alert('You must provide a start date');
	return false;
    }

    if (!validate_date(startDate)) {
	alert('Invalid start date format');
	return false;
    }

    if (check_blank(endDate) && !validate_date(endDate)) {
	alert('Invalid end date format. Leave it blank if even is only on one day.');
	return false;
    }

    if (!check_blank(title)) {
	alert('You must provide a title');
	return false;
    }

    if (!check_blank(description)) {
	alert('You must provide a description');
	return false;
    }
}

function validateDonationYear() {

    var year = document.configForm.year.value;

    if (!check_blank(year)) {
	alert('Donation Year cannot be blank.');
	return false;
    }
    
    else if ((year.length == 4) && (isInteger(year))) {
	return true;
    }

    else {
        alert('Donation Year must be 4 digits');
	return false;
    }
}

function validateDonationPoint() {

    var donationPoint = document.pointForm.donationPoint.value;

    if (!check_blank(donationPoint)) {
	alert('Donation Point cannot be blank.');
	return false;
    }
    
    return true;
}

