/*
    Gets the selected radio value
*/
function getRadioValue(radio) {
    if(radio == null) {
        return "";
    } else if(radio.length) {  //multiple
        for (var i=0; i < radio.length; i++) {
            if(radio[i].checked) {
                return radio[i].value;
            }
        }
    } else if(radio.checked) {
        return radio.value;
    }

    return "";
}    

/*
    Gets the checbox values as comma separated string
*/
function getCheckboxValues(checkbox) {
    if(checkbox == null) {
        return "";
    } else if(checkbox.length) {  // multiple
        var values = "";

        for (var i=0; i < checkbox.length; i++) {
            if(checkbox[i].checked) {
                values += "," + checkbox[i].value;
            }
        }

        if(values.length > 0) {
            return values.substr(1);
        }
    } else if(checkbox.checked) {
        return checkbox.value;
    }

    return "";
  }


  function doSameAs(check, form, idName) {
    for(i=0; i < form.elements.length; i++){
      if(form.elements[i].id == idName) {
        if(check.checked) {
		  if(form.elements[i].type.indexOf("select") != -1) {//Select
	        form.elements[i].selectedIndex = 0;
          } else { //For now, everything else assume as "text"
	        form.elements[i].value = '';
          }
        }
 	    form.elements[i].disabled = (check.checked);
     }
    }
  }

function getDateObject(year,month,day){
 var date =new Date();
 date.setYear(year);
 date.setMonth(month-1);
 date.setDate(day);
 return date;
}
function getNewerDate(date1,date2){
if(date1.getYear()>date2.getYear())
return 1;
else if(date2.getYear()>date1.getYear())
return 2;
else if(date1.getMonth()>date2.getMonth())
return 1;
else if(date2.getMonth()>date1.getMonth())
return 2;
else if(date1.getDay()>date2.getDay())
return 1;
else if(date2.getDay()>date1.getDay())
return 2;
return 0;
}
function isValidPostalCode(code) {
  if(code.length == 0) {return true;}
  return checkPostalCode(code);
}
function isValidPhone(num) {
  if(num.length == 0) {return true;}
  return checkPhoneNum(num);
}
function isValidEmail (emailStr) {
  if(emailStr.length == 0) {return true;}
  return checkEmailAddress(emailStr);
}
///////////

function checkPostalCode(code) {
  rePCode1 = /^[a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d$/   // w/o space
  rePCode2 = /^[a-zA-Z]\d[a-zA-Z] \d[a-zA-Z]\d$/  // W/ space
  rePCode3 = /^[a-zA-Z]\d[a-zA-Z]-\d[a-zA-Z]\d$/  // with hipen

  return rePCode1.test(code) || rePCode2.test(code) || rePCode3.test(code);
}

function checkEmailAddress (emailStr) {
  reEmail= /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,5})(\]?)$/;
  return reEmail.test(emailStr);
}

function checkPhoneNum(str) {
  str = stripPhoneNumber(str);
  var num = parseInt(str);

  if(isNaN(num)) {
	  return false;
  }
  return (num > 999999999 && num < 20000000000); //100-000-000 1-999-999-999
}

function stripPhoneNumber(s) {
    var returnString = "";
    var phoneNumberDelimiters = "()- ";
    for (var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (phoneNumberDelimiters.indexOf(c) == -1) {returnString += c};
    }
    return returnString;
}

//////////
function checkRange(str, from, to) {
  var value = parseFloat(str.replace(/,/, ""));
  if(isNaN(value)) {
	  return false;
  }
  return (value >= from && value <= to);
}

function isPlusNum(str) {
	var num = parseFloat(str.replace(/,/, ""));
	if(isNaN) {
		return false;
	}
	return num >= 0;
}

//
// Check date is valid
// month - starts from 1, so need to minus -1
function isValidDate(year, month, day) {
  month -= 1;

  var date = new Date(year, month, day);

  if(isNaN(date)) {
	return false;
  }

  //Check date if it is like April 31
  return (month == date.getMonth());
}

function checkDateRange(date, from, to) {
  return (date >= from && date <= to);
}

function isDateAfter(date, target) {
  return (date >= target);
}

function isDateBefore(date, target) {
  return (date <= target);
}

function isFutureDate(date) {
    var now = new Date();
    return (date > now);
}

function checkFields(phoneNum) {
   var regExp = /\d{3}-\d{3}-\d{4}/g;

   if (phoneNum.search(regExp) == -1 || phoneNum == "")  {
		 return false;
   }
   return true;
}

function checkPhoneNumEx(phoneNum) {
   var regExp = /\d{3}-\d{3}-\d{4}/g;

   if (phoneNum.search(regExp) == -1 || phoneNum == "")  {
		 return false;
   }
   return true;
}


function hasSpecialChars(str) {
	return (str.indexOf("'") != -1)
			|| (str.indexOf(" ") != -1);
}

function hasSpecialCharsEx(str) {
	//if (str.indexOf("'") != -1)		return true;
	if (str.indexOf("~") != -1)		return true;
	if (str.indexOf("`") != -1)		return true;
	if (str.indexOf("!") != -1)		return true;
	if (str.indexOf("@") != -1)		return true;
	if (str.indexOf("#") != -1)		return true;
	if (str.indexOf("$") != -1)		return true;
	if (str.indexOf("%") != -1)		return true;
	if (str.indexOf("^") != -1)		return true;
	if (str.indexOf("&") != -1)		return true;
	if (str.indexOf("*") != -1)		return true;
	if (str.indexOf("(") != -1)		return true;
	if (str.indexOf(")") != -1)		return true;
	if (str.indexOf("?") != -1)		return true;
	if (str.indexOf(">") != -1)		return true;
	if (str.indexOf("<") != -1)		return true;


	return false;
}


function checkPasswords(login, pwd1, pwd2) {
	var msg = "";

	if(hasSpecialChars(pwd1)) {
		msg += "Password should not have apostrophe or space.\n";
	}

	if(pwd1.length < 6 || pwd2.length > 20) {
		msg += "Password should be 6-20 characters.";
	} else if (pwd1 == login) {
		msg += "Password should not be same as user name.\n";
	} else if (pwd1 != pwd2) {
		msg += "Two passwords do not match each other.";
	}

	return msg;
}

/*************************function to trim string by hany********************************/
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


function trim(value) {
   return value.replace(/^\s+/,'').replace(/\s+$/,'');

}


/*
*authour: ismail
*the function initially developed to resolve a bug
*however it can be extended to check for more data types.
*to check for some data type, give the data field the proper id and title
* update this function as the follwing to check for more types
* the id of the input should be set as the following:
* REQUIRED
* PHONE_REQUIRED
* PHONE
* POSTAL_CODE_REQUIRED
* POSTAL_CODE
* and the the titles should be set to the field display name
* for example for a required official name
* <input id='REQUIRED' title='Official Name'>
*/
function validateFormEx(form, doRequired, doPhone, doPostalCode){
    var formFields      = form.elements;
    var field           = null;
    var requiredMsg     = '\n-The following fields are required:\n';
    var phoneMsg        = '\n-The following phone numbers are not valid:\n';
    var PostalCodeMsg   = '\n-The following postal codes are not valid:\n';
    var isRequiredOk    = true;
    var isPhoneOk       = true;
    var isPostalCodeOk  = true;
    var isValidForm     = false;
    var errorMsg        = '';
    var firstBadField   = null;
    var isRequired      = null;

    for(i=0; i<formFields.length; i++){//for each field
        field = formFields[i];
       /*********** trim before checking by Hany ************************/
       if(null!=field.value){
        if(field.type!="file"){
            field.value=trim(field.value);
        }
      }

        /*******************************************************************/
        if( (null==field.id) || (''==field.id) ){//field id not set
            continue;
        }//field id not set

        isRequired = ( -1 < field.id.indexOf("REQUIRED", 0) );
        if( (!isRequired) &&  ( (null==field.value)||(0==field.value.length) )
          ){//if field is not required and not set
            continue;
        }


        if( (1==doRequired) && (isRequired) ){//check required
            if(0==field.value.length){
                requiredMsg += field.title + '\n';   isRequiredOk = false;
                if(null==firstBadField) firstBadField = field;
            }
         continue;
        }//check required

        if((1==doPhone) &&
           ( ('PHONE_REQUIRED' == field.id) || ('PHONE' == field.id) )
           ){//check the phone number
            if(false == checkPhoneNumEx(field.value)){
                phoneMsg += field.title + '\n';   isPhoneOk = false;
                if(null==firstBadField) firstBadField = field;
            }//check the phone number.
         continue;
        }//check the phone number

        if( (1==doPostalCode) &&
            ( ('POSTAL_CODE_REQUIRED'==field.id) || ('POSTAL_CODE'==field.id) )
          ){//check postal code
            if(false == checkPostalCode(field.value)){
                PostalCodeMsg += field.title + '\n';   isPostalCodeOk = false;
                if(null==firstBadField) firstBadField = field;
            }
         continue;
        }//check postal code

    }//for each field

    isValidForm = isRequiredOk && isPhoneOk && isPostalCodeOk;

    if(false == isRequiredOk)   errorMsg += requiredMsg;
    if(false == isPhoneOk)      errorMsg += phoneMsg;
    if(false == isPostalCodeOk) errorMsg += PostalCodeMsg;

    if(false==isValidForm){
    	var canGetFocus =	(null 		!= firstBadField) &&
    						('hidden' 	!= firstBadField.type) &&
    						(false 		== firstBadField.disabled);

        if(true==canGetFocus){
			firstBadField.focus();
			}


        alert(errorMsg);
        return false;
    }else{
        alert("Your record has validated successfully, thank you.");
        return true;
    }
}


////////////////////////////////////////////////////////
//  Control functions to check user input as they typed
//  onkeypress="return checkNumeric(this, event)" 
////////////////////////////////////////////////////////

// http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

function checkIneger(input, evt, msg) {
    var keyCode = getKeyCode(evt);

    // control keys to skip
    if (isControlKey(keyCode)) {
        return true;
    }

    var keyChar = String.fromCharCode(keyCode);
    var value = getInputText(input, keyChar);

    //value = value.replace(/,/, "");  //Allow comma

    if(msg == null) {
            msg = "This is a numeric field, only numbers can be entered."; 
    }

    if(value == "-" || value == "") {
        return true;
    } else if(isNaN(value)) {
        alert(msg);
        return false;
    } // ELSE
    var i = parseInt(value);
    var f = parseFloat(value);

    if(i != f) {
        alert(msg);
        return false;
    }
    return true;
}

function checkNumeric(input, evt, msg) {
    var keyCode = getKeyCode(evt);

    // control keys to skip
    if (isControlKey(keyCode)) {
        return true;
    }

    var keyChar = String.fromCharCode(keyCode);
    var value = getInputText(input, keyChar);

    value = value.replace(/,/, "");  //Allow comma

    if(value == "-" || value == "") {
        return true;
    } else if(isNaN(value)) {
        if(msg == null) {
            msg = "This is a numeric field, only numbers can be entered."; 
        }
        alert(msg);
        return false;
    }

    return true;
}

// Private
function getKeyCode(evt) {
    if (window.event) {
       return window.event.keyCode;
    } else if (evt.which) {
       return evt.which;
    }
    return null;
}

// Private
function isControlKey(keyCode) {
    return (keyCode==null) 
            || (keyCode==0)   //Most of control keys
            || (keyCode==8)   //backspace 
            || (keyCode==9)   //Tab
            || (keyCode==13)  //Enter
            || (keyCode==27); //escape
}

/**
* Private
* Gets the after value after event like onkeypress.
*
*/
function getInputText(input, keyChar) {
    var start = getSelectionStart(input);
    var end = getSelectionEnd(input);

    var val = input.value;
    return val.substring(0, start) + keyChar + val.substring(end);
}


////////////////////////////////////////////////////////
// http://javascript.nwbox.com/cursor_position/
////////////////////////////////////////////////////////

// Private
function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}

// Private
function getSelectionEnd(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -o.value.length)
		return r.text.length
	} else return o.selectionEnd
}

function selectAll(targets, chk){
    if(targets.length) {
        for (var i=0; i < targets.length;i++){
            targets[i].checked = chk;
        }
    } else {
        targets.checked = chk;
    }
}

function letternumber(e)
{
var key;
var keychar;

if (window.event)
    key = window.event.keyCode;
else if (e)
    key = e.which;
else
    return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
    return true;

// alphas and numbers
else if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) > -1))
    return true;
else
    return false;
}


function isDateEmpty(form, name) {
    var year = form[name + "year"].selectedIndex;
    var month = form[name + "month"].selectedIndex;
    var day = form[name + "day"].selectedIndex;

    return (year == 0 || month == 0 || day == 0);
}

