//***********************************************************************
// common.js
// This is a collection of commonly used utilities which includes string
// manipulation, email format validation, password format validation etc
// To ensure that these functions are generic and highly reusable, there
// will only be validation logic and no custom error or warning messages
// being output from the functions.
//***********************************************************************

// -----> Common Function <-----

// return true if the string is not empty
function isEmpty(str){
	var ss = trim(str)
    return (ss==undefined) || (ss == null) || (ss == '');
}

// returns true if the string is a valid email
function isValidEmail(str){
	if(isEmpty(str)) return false;
	
	//var reg1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	//var reg2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2})");
	//return (!reg1.test(str) && reg2.test(str));
	
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	return re.test(str);
}

// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
    var re = /[^a-zA-Z]/g
    if (re.test(str)) return false;
    return true;
}

// returns true if the string only contains characters 0-9
function isNumeric(str){
    var re = /[\D]/g
    if (re.test(str)) return false;
    return true;
}

// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
    var re = /[^a-zA-Z0-9]/g
    if (re.test(str)) return false;
    return true;
}

// returns if the string is decimal
function isDecimal(str) {
    var re = /^\d*(\.\d+)?$/g
    return re.test(str);
}

// returns true if the string is a valid date formatted as...
// dd/mm/yyyy
function isDate(str){
    var pos1 = str.indexOf("/");
    var pos2 = str.indexOf("/",pos1+1);
    if(pos1 == -1 || pos2 == -1) {return false};
    
    var d = str.substring(0,pos1);
    var m = str.substring(pos1+1,pos2);
    var y = str.substring(pos2+1);
    
    if(m < 1 || m > 12 || y < 1900 || y > 2100) return false;
    if(m == 2){
        var days = ((y % 4) == 0) ? 29 : 28;
    }else if(m == 4 || m == 6 || m == 9 || m == 11){
        var days = 30;
    }else{
        var days = 31;
    }
    return (d >= 1 && d <= days);
}

function isRadioButtonEmpty(obj) {
	var i = obj.length;
	for (var j=0; j<i; j++) {
		if (obj[j].checked) { return false; }
	}
	obj[0].focus();
	return true;
}

function isCheckBoxEmpty(id) {
/*
	for (i = 1; i < objArr.length; i++) {
		if (objArr[i].checked) { return false; }
	}
	return true;
*/	
	var index = 0;
	while(document.getElementById(id+"_"+index) != undefined) {
		if(document.getElementById(id+"_"+index).checked) { return false; }
		index++;
	}
	document.getElementById(id+"_0").focus();
	return true;
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		alert("not a number");
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function hasSpecialCharacters(textstring) {
    var specialstring = "<>\"';()%&";
    if( !textstring ) { return false; }
    if( textstring.length <= 0 ) { return false; }
    for(j=0; j<specialstring.length; j++) {
        if( textstring.indexOf(specialstring.charAt(j)) != -1 ) { return true; }
    }
    return false;
}

/**
 * Performs left trim of a string to remove whitespaces
 */
function ltrim(str) {
	if (str==null){return str;}
	for (var i=0; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\r" || str.charAt(i)=="\t"; i++);
	return str.substring(i,str.length);
}

/**
 * Performs right trim of a string to remove whitespaces
 */
function rtrim(str) {
	if (str==null){return str;}
	for (var i=str.length-1; str.charAt(i)==" " || str.charAt(i)=="\n" || str.charAt(i)=="\r" || str.charAt(i)=="\t"; i--);
	return str.substring(0,i+1);
}

/**
 * Trim leading and trailing whitespaces of a string
 */
function trim(s) { return ltrim(rtrim(s)); }

/**
 * Open a pop up window
 */
function winopen(tgturl, tgtname, tgtwidth, tgtht) {
  var startX = (window.screen.availWidth  - tgtwidth)/2;
  var startY = (window.screen.availHeight - tgtht)/2;
  var features = "top=" + startX + ",left=" + startY + ",width=" + tgtwidth + ",height=" + tgtht + ",toolbar=no,menubar=no,location=no,status=no,resizable=no,scrollbars=no";
  window.open(tgturl, tgtname,features);
}

function showMe(elementId)
{
	var obj = document.getElementById(elementId);
	obj.style.display = "block";
	
}
function hideMe(elementId)
{
	var obj = document.getElementById(elementId);
	obj.style.display = "none";
	
}
function showMeInLine(elementId)
{
	var obj = document.getElementById(elementId);
	obj.style.display = "inline";

}
function hideMeInLine(elementId)
{
	var obj = document.getElementById(elementId);
	obj.style.display = "none";
}

function showOrHideMe(elementId)
{
	var obj = document.getElementById(elementId);
	if(obj.style.display == "block")
	{
		obj.style.display = "none";
	}
	else
	{
		obj.style.display = "block";
	}
}

// -----> Specific to Promotions <-----
var TEXTBOX = 1;
var EMAIL = 2;
var NUMERIC = 3;
var AMOUNT = 4;	
var RADIO_BUTTON = 5;
var CHECK_BOX = 6;
var DROPDOWN = 7;
var MAX_VALUE = 9999999;

// Password condtion set by Visa
// 1. Minimum : 6 characters
// 2. Maximum : 25 characters
// 3. No white space
// 4. No special characters
// 5. Only A-Za-z0-9	
function isValidPassword(p) {
	if (isEmpty(p)) { return false; }
	if (p.length < 6 || p.length > 25) { return false; }
	return isAlphaNumeric(p);
}

// return true if the string is the currency
// eg: 100 , 100.12 , .12   -> true
//     100. ,100.123        -> false
function isCurrency(str){
    //START Old code
    //var re = /^\d*(\.\d\d)?$/g
    //END Old code
    
    //START New regexp for currency
    var re = /^\d*(\.\d{1,2})?$/;
    //END New regexp for currency
    return re.test(str);
}

// to check the field in the form is empty (for textbox) or seleced (for radio button, check box and dropdown)
// the first argument is the type of the field
// for check box, the second argument is the id (prefix) of the check box in the form
// for others, the second argument is the object in the form
function isFieldEmpty() {
	type = arguments[0];

	if (type == RADIO_BUTTON) {
		var obj = arguments[1];		
		return isRadioButtonEmpty(obj);
	} else if (type ==  CHECK_BOX) {
		return isCheckBoxEmpty(arguments[1]);
	} else if (type == TEXTBOX || type == EMAIL || type == NUMERIC || type == AMOUNT || type == DROPDOWN) {
		var obj = arguments[1];
		if(isEmpty(obj.value)) { obj.focus(); return true; }
		else { return false; }
	}
	
	return true;
}

// to check the field in the form has valid value (for textbox only)
// the first argument is the type of the field
// the second argument is the object in the form
function isFieldValueValid(type, obj) {
	// only need to check when the user enter the value
	if (isEmpty(obj.value)) return true;

	if (type == EMAIL) {
		if (!isValidEmail(obj.value)) { obj.focus(); return false; }
		else { return true; }
	} else if (type == NUMERIC) {
		if (!isNumeric(obj.value)) { obj.focus(); return false; }
		else { return true; }
	} else if (type == AMOUNT) {
		if (!isCurrency(obj.value)) { obj.focus(); return false; }
		else { return true; }
	}
	return true;
}

function isWithinRange(obj, min, max) {
	// only need to check if the user enter the value
	if (isEmpty(obj.value)) return true;
	
	if (obj.value >= min && obj.value <= max) { return true; }
	else { obj.focus(); return false; }
}

function isLessThanOrEqualMax(obj, max) {
	// only need to check if the user enter the value
	if (isEmpty(obj.value)) return true;
	
	if (obj.value <= max) { return true; }
	else { obj.focus(); return false; }
}

function isGreaterThanMin(obj, min) {
	// only need to check if the user enter the value
	if (isEmpty(obj.value)) return true;
	
	if (obj.value > min) { return true; }
	else { obj.focus(); return false; }
}

function isGreaterThanOrEqualMin(obj, min) {
	// only need to check if the user enter the value
	if (isEmpty(obj.value)) return true;
	
	if (obj.value >= min) { return true; }
	else { obj.focus(); return false; }
}

function redirect(url)
{
	window.location=url;	
}

function convertToDate(d) {
	var firstIndex = d.indexOf("/");
	var secondIndex = d.lastIndexOf("/");
	var date1 = d.substring(0, firstIndex);
	var month1 = d.substring(firstIndex+1, secondIndex);
	var year1 = d.substring(secondIndex+1, d.length);
	var dObj = new Date();
	dObj.setFullYear(year1,month1-1,date1);
	return dObj;
}

// return true if d1 is less than or equal to (earlier than or the same date as) d2
function isDateLessThan(d1, d2) {
	var dObj1 = convertToDate(d1);
	var dObj2 = convertToDate(d2);
	return dObj1 < dObj2;
}

function isEarlierThanToday(d) {
	var today = new Date();
	var toCompare = convertToDate(d);
	return toCompare < today;
}
