// JavaScript functions

// global variables
var MonthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

function checkForgotPasswordForm() {
  with (window.document.frmForgotPassword) {
    if (isEmpty(txtLoginId, 'Please enter your Login Id')) {
      return;
    } else if (!validateEmail(txtEmail)) {
      return;
    } else {
      window.document.frmForgotPassword.action = "forgot_password.php";
      submit();
    }
  }
}

function checkLoginForm() {
  with (window.document.login_action) {
    if (isEmpty(ffLoginId, 'Please enter your Login Id')) {
      return;
    } else if (isEmpty(ffPassword, 'Please enter your password')) {
      return;
    } else {
      window.document.login_action.action = "login_action.php";
      submit();
    }
  }
}
function checkSaveUserForm() {
	with (window.document.frmRegisterUser) {
		
		var formGo = false;
		
	//validate login name
		var loginRegEx = /[^a-zA-Z0-9_\.\-]/;
		if ( txtLoginId.value == null || txtLoginId.value == "" ) {
			errMsg += 'Please enter your Login Id';
			alert ('Please enter your Login Id');
			return false;
		}
		if(txtLoginId.value.match(loginRegEx) ){
			alert ('Your login ID must use only the following characters:\n -upper or lowercase letters\n -numbers\n -any of these characters: _-.');
			return false;
		}else{
			formGo = true;
		}
		
		
	//validate passwords
		if (txtPassword.value == null || txtPassword.value == "" ) {
			alert('Please enter your password');
			return false;
		} else if (txtConfirmPassword.value == null || txtConfirmPassword.value == "" ) {
			alert('Please confirm your password');
			return false;
		}
		if (txtPassword.value != txtConfirmPassword.value) {
			alert("Password and Confirm password do not match");
			return false;
		}else{
			formGo = true;
		}
		
		
	//validate names
		var nameRegEx = /[^a-zA-Z0-9_\.\-\(\)\+\s]/;
		if (txtName.value == null || txtName.value == "" ) {
			alert('Please enter your name');
			return false;
		}
		if(txtName.value.match(nameRegEx) ){
			alert ('Your name must use only the following characters:\n  -upper or lowercase letters\n  -numbers\n  -any of these characters: _-.()+');
			return false;
		}else{
			formGo = true;
		}
		
		
	//validate adress
		
		if (txtCity.value == null || txtCity.value == "" ) {
			 alert('Please enter the city');
			return false;
		}
		if(txtCity.value.match(nameRegEx) ){
			alert ('The city name you have entered is invalid.');
			return false;
		}else{
			formGo = true;
		}
		
		
		if(lstState.value == null || lstState.value == "" ) {
			alert ('Please select a state');
			return false;
		}else{
			formGo = true;
		}
		if(lstCountry.value == null || lstCountry.value == "" ) {
			alert('Please select a country');
			return false;
		}else{
			formGo = true;
		}
		
		
	//validate Zip and Postal codes
		var zipRegEx = /(^\d{5}(-\d{4})?$)|(^[A-Za-z]{1}\d{1}[A-Za-z]{1} *\d{1}[A-Za-z]{1}\d{1}$)/;//conforms to US-5 and US-9 zip code, OR canada postal code format
		var pcodeRegEx = /(^[A-Za-z]{1}\d{1}[A-Za-z]{1}\d{1}[A-Za-z]{1}\d{1}$)/;//conforms to US-5 and US-9 zip code, OR canada postal code format
		if (txtZip.value == null || txtZip.value == "" ) {
			alert('Please enter the Zip Code');
			return false;
		}
		if(txtZip.value.match(pcodeRegEx) ){
			alert('Candian postal codes in the database must have a space in the middle. Please add a space to continue.');
			return false;
		}
		if(txtZip.value.match(zipRegEx) ){
			formGo = true;
		}else{
			alert ('Your ZIP/postal code is invalid.');
			return false;
		}
		
		
	//validates email
		if (!validateEmail(txtEmail)) {
			return false;
		}
		
		
	//validates phone number
		if (!validatePhone(txtTelephone)) {
			return false;
		}
		
		
	//validates company summary
		if (txaCompanySummary.value == null || lstState.value == "" ) {
			alert ('Please enter your Company Summary');
			return false;
		} else {
			submit();
		}
	}
}

function checkModifyUserForm() {
  with (window.document.frmModifyUser) {
    if (isEmpty(txtCompanyName, 'Please enter your company name')) {
      return;
    } else if (isEmpty(txtName, 'Please enter your first name')) {
      return;
    } else if (isEmpty(txtAddress1, 'Enter your Address')) {
      return;
    } else if (isEmpty(txtCity, 'Please enter the city')) {
      return;
    } else if (isEmpty(txtZip, 'Please enter the Zip Code')) {
      return;
    } else if (isEmpty(lstState, 'Please select a state')) {
      return;      
    } else if (isEmpty(lstCountry, 'Please select a country')) {
      return;
    } else if (!validatePhone(txtTelephone)) {
      return;
    } else if (!validateFax(txtFax)) {
      return;
    } else if (!validateEmail(txtEmail)) {
      return;
    }
    
    // check for valid website
    var website_link = txtWebsite.value;
    if (website_link != '' && website_link.substring(0,7) != "http://")
    {
      alert("Your website name must start with http://");
      return;
    }      
    else 
    {
      submit();
    }
  }
}

function checkBusinessProfile() {
    with (window.document.frmBusinessProfile) {
    if (isEmpty(lstBusinessType, 'Please select a Business Type')) {
      return;
    } else if (isEmpty(txtExpInYrs, 'Please enter the Years of Experience')) {
      return;
    } else if (isEmpty(txtServices, 'Please enter the Services you offer')) {
      return;
    } else {
      submit();
    }
  }
}

function toggleOther()
{
  otherDivId = document.getElementById('businessOther');
  if(document.frmBusinessProfile.lstBusinessType.value == 'Other')
  {
    otherDivId.style.display = 'block';  
  }
  else
  {
    otherDivId.style.display = 'none'; 
  }
}

function addUser() {
  window.location.href = 'indexUser.php?view=add';
}


function deleteUser(clientId) {
  if (confirm('Delete this user?')) {
    window.location.href = 'controller.php?action=delete&clientId=' + clientId;
  }
}

/*
Strip whitespace from the beginning and end of a string
Input : a string
*/
function trim(str) {
  return str.replace(/^\s+|\s+$/g,'');
}

/*
Make sure that textBox only contain number
*/
function checkNumber(textBox) {
  while (textBox.value.length > 0 && isNaN(textBox.value)) {
    textBox.value = textBox.value.substring(0, textBox.value.length - 1)
  }
  textBox.value = trim(textBox.value);
}

function isEmpty(formElement, message) {
 formElement.value = trim(formElement.value);
  _isEmpty = false;
  if (formElement.value == '') {
    _isEmpty = true;
    alert(message);
    formElement.focus();
  }
  return _isEmpty;
}

/*
  Set one value in combo box as the selected value
*/
function setSelect(listElement, listValue) {
  for (i=0; i < listElement.options.length; i++) {
    if (listElement.options[i].value == listValue)  {
      listElement.selectedIndex = i;
    }
  } 
}

/* Check for radio elements */

function checkRadio(radElement, message) 
{
  var ele_value = false;
  _isNotSelected = false;
  for (i=0; i < radElement.length; i++) 
  {
    if (radElement[i].checked)  
    {
      ele_value = radElement[i].value;
    }
  }
  if (!ele_value)
  {
    alert(message);
    _isNotSelected = true;
  }
  return _isNotSelected;
}

function signUp() 
{
  window.location.href = 'register_user_form.php';
}

function forgotPassword() 
{
  window.location.href = 'forgot_password.php';
}

function checkPassword()
{
  theForm = window.document.frmPassword;
  if (theForm.txtOldPassword.value == '') {
     alert('Enter current password');
     theForm.txtOldPassword.focus();
     return false;
  } else if (theForm.txtNewPassword1.value == '') {
     alert('Enter new password');
     theForm.txtNewPassword1.focus();
     return false;
  } else if (theForm.txtNewPassword2.value == '') {
     alert('Repeat new password');
     theForm.txtNewPassword2.focus();
     return false;
  } else if (theForm.txtNewPassword1.value != theForm.txtNewPassword2.value) {
     alert('New password don\'t match');
     theForm.txtNewPassword2.focus();
     return false;
  } else {
      submit();
  }
}

 // Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s) {   
  var i;
    for (i = 0; i < s.length; i++) {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag) {   
  var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++) {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone) {
  s=stripCharsInBag(strPhone,validWorldPhoneChars);
  return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function validatePhone(phoneNo) {
  if ((phoneNo.value==null)||(phoneNo.value=="")) {
    alert("Please enter your Phone Number")
    phoneNo.focus()
    return false
  }
  if (checkInternationalPhone(phoneNo.value)==false) {
    alert("Please enter a Valid Phone Number")
    phoneNo.value=""
    phoneNo.focus()
    return false
  }
  return true
 }

function validateFax(faxNo) {
  if ((faxNo.value==null)||(faxNo.value=="")) {
  } else {
    if (checkInternationalPhone(faxNo.value)==false){
      alert("Please enter a Valid Fax Number")
      faxNo.value=""
      faxNo.focus()
      return false
    }
  }
  return true
 }

function validateEmail(emailID) {
	var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(emailID.value.match(emailRegEx)){
		return true;
	}else{
		alert('Please enter a valid email address.');
		return false;
	}
}

function checkUploadPhotoForm() 
{
  with (window.document.frmUploadPhoto) 
  {
    window.document.frmUploadPhoto.action = "upload_photo_action.php";
    submit();
  }
} 

function back2UploadPage() 
{
  with (window.document.frmUploadPhotoAction) {
      window.document.frmUploadPhotoAction.action = "upload_photo_form.php";
      submit();
  }
}

function back2ManagePhotosPage(photoId) 
{
  with (window.document.frmUploadPhoto) {
      window.document.frmUploadPhoto.action = "manage_photos.php?ffPhotoId=" + photoId;
      submit();
  }
}

function checkRatingForm(userId, link_var, link_val) 
{
  with (window.document.frmContractorDetails) 
  {
    if (checkRadio(rate_timeliness, 'Please rate the contractor\'s timeliness')){
      return;
    } else if (checkRadio(rate_cleanliness, 'Please rate the contractor\'s cleanliness')) {
      return;
    } else if (checkRadio(rate_budget, 'Please rate how did the contractor do on his budget')) {
      return;
    } else if (checkRadio(rate_quality, 'Please rate the contractor\'s quality of work')) {
      return;
    } else if (checkRadio(rate_communication, 'Please rate the contractor\'s communication')) {
      return; 
    } else if (isEmpty(txaYourReview, 'Please enter your review comments')) {
      return;      
    } else if (isEmpty(txtName, 'Please enter your name')) {
      return;
    } else if (isEmpty(txtCity, 'Please enter the City')) {
      return;
    } else if (isEmpty(txtState, 'Please enter the State')) { 
      return;
    } else if (isEmpty(txtCountry, 'Please enter the Country')) {
      return; 
    } else if (!validatePhone(txtTelephone)) {
      return;      
    } else {
      document.frmContractorDetails.submitted.value = "TRUE";
      document.frmContractorDetails.action = "contractor_details.php?cid=" + userId + "&activetab=rateus_tab" + "&back_link_var=" + link_var + "&back_link_val=" + link_val;
      submit();
    }
  }
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) 
  {
    var pair = vars[i].split("="); 
    if (pair[0] == variable) 
    {
      return pair[1];
    }
  } 
  return "";
}

function open_ad_in_new_window(page_name)
{
  var win = window.open(page_name);
  win.resizeTo(800, 600);
}

function checkFeedbackForm() 
{
  with (window.document.frmFeedback) 
  {
    if (isEmpty(txaYourReview, 'Please enter your feedback comments')) {
      return;
    }
    else
    {
      window.document.frmFeedback.action = "publish_ratings_action.php";
      submit();
    }
  }
} 

function validatezip()
{
// Lets make sure a Zip Code is entered:
var zip = document.form2.zip.value;
if (zip == "")
{
alert("Please enter a Zip Code or Postal Code to continue.");
document.form2.zip.focus();
return false;
}
return true;
}