/*============================================================================
 *  Useful script functions
 ===========================================================================*/

var email = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var zipcode = /^\d{5}(-\d{4})?$/;
var phone = /^\d+$/;
//var money = /^\$?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{1,2})?$/;
var date = /^(([1-9])|(0[1-9])|(1[0-2]))\/(([1-9])|(0[1-9])|([1-3][0-9]))\/((\d{4}))$/;
var ccard = /^((4\d{3})|(5[1-5]\d{2})|(6011))-?\d{4}-?\d{4}-?\d{4}|3[4,7]\d{13}$/;
var cvv = /^\d{3,4}$/;
var ccexp = /^(([1-9])|(0[1-9])|(1[0-2]))\/(((0[1-9])|([1-3][0-9])))$/;
var ccexp2 = /^((0[1-9])|(1[0-2]))((0[1-9])|([1-3][0-9]))$/;
var numeric = /^\d/;

/*============================================================================
 *  Identity No / IC related
 ===========================================================================*/

 // Restrict user from entering '-' on IC
function enterIC(obj, country) {
	
  var result = obj.value;
	
	if (country.value == 'MY') {
	  if (result.indexOf("-") >= 0) {
	    var parseStr = "";
	    
	    for (var i=0; i<result.length; i++) {
	      if (result.charAt(i) != "-")
	       parseStr = parseStr + result.charAt(i);
	    }
	    
	    result = parseStr;
	    obj.value = result;
	  }
	}
}
 
/*============================================================================
 *  Payment Mode related
 ===========================================================================*/
 
// luhn cc validator
function ccValidator(ccnum) {
	var checkSum = 0;
	var iMult = 0;
	
	ccnum = Trim(ccnum);
	if(ccnum.length <= 0) return false;
	for(var i=ccnum.length;i>0;i--) {
		iDigit = (iMult % 2 + 1) * parseInt(ccnum.substring(i-1,i));
		checkSum += (iDigit > 9) ? (iDigit - 9) : iDigit;
		iMult++;
	}//for
	return (checkSum % 10 == 0) && (checkSum > 0);
} //ccValidator
      
/*============================================================================
 *  Member related
 ===========================================================================*/

function validateLocationID(obj) 
{
	var validId = /^([a-z|0-9]{2,5})$/i;
	var vl = TrimAll(obj.value);
	if (vl == "")
		return false;
	obj.value = vl;
	return validId.test(vl);
}

function validateRegisterPrefix(obj) 
{
	var validId = /^([a-z]{3})$/i;
	var vl = TrimAll(obj.value);
	if (vl == "")
		return false;
	obj.value = vl;
	return validId.test(vl);
}

// Restrict user from entering \s on Id
function enterMemberId(obj) {
  
  var result = obj.value;

  if (result.indexOf(" ") >= 0) {
    var parseStr = "";
    
    for (var i=0; i<result.length; i++) {
      if (result.charAt(i) != " ")
        parseStr = parseStr + result.charAt(i);
    }
    
    result = parseStr;
    obj.value = result;
  }
}

function validateMemberIdRunningNo(obj) {

	var validCode = /\d+$/;
	
	var vl = TrimAll(obj.value);
	
	cnt = vl * 1;
	
	if (cnt <= 0)
		return false;
	else {	
		return validCode.test(vl);
	}
}

function validateMemberId(obj) {

	var validId = /^([a-z]{2}\d{10})$/i;
	
	var vl = TrimAll(obj.value);

	if (vl == "")
		return false;
  
	vl = vl.toUpperCase();

	if (vl != "HQ")	{
		if (vl.length < 7  || vl.length > 12 ) {
			return false;
		} else {
			return true;
		}
	} else {
		return true;
	}
	
	/*if (vl != "HQ")
		return validId.test(vl);
	else 
		return true;*/
}

function validateStockistId(obj) {

	var validId = /^([A-Z|0-9]{6})$/i;

	var vl = TrimAll(obj.value);

	if (vl == "")
		return false;
	
	obj.value = vl.toUpperCase();
	return validId.test(vl);
}

function validateStockistIdOnlyNumbers(obj) {

	var validCode = /^([A-Z|0-9]{5})$/i; // /\d{5}$/;
	
	var vl = TrimAll(obj.value);
	
	obj.value = vl.toUpperCase();
	return validCode.test(vl);
}

function validateStockistUserId(obj) {

	var validId = /^([A-Z|0-9]{4,10})$/i;

	var vl = TrimAll(obj.value);

	if (vl == "")
		return false;
  
	vl = vl.toUpperCase();

	if (vl != "HQ")
		return validId.test(vl);
	else 
		return true;
}

function validateAdminUserId(obj) {

	var validId = /^([a-z|0-9]{4,10})$/i;

	var vl = TrimAll(obj.value);

	if (vl == "")
		return false;

	obj.value = vl;
	
	if (vl != "HQ")
		return validId.test(vl);
	else 
		return true;
}

// Standard check alphanumeric only
function validateId(obj) {
	
	var validId = /^([a-z|0-9]{4,10})$/i;

	var vl = obj.value; //TrimAll(obj.value);

	if (vl == "")
		return false;

	obj.value = vl;	
	return validId.test(vl);
}

function validateMemberRegisterFormNo(obj) {
	
	return true;
	
	/*
	var vl = Trim(obj.value);
	
	if (vl == "") {
    alert("Invalid Member Register Form No.");
    focusAndSelect(obj);
    return false;
	} else
		return true;
	*/
}

function validateMemberIntroducer(intrID, intrIdentityNo, missing) {
	
	
	
	if (missing == "0") { // No missing introducer is allow during registration
		var chkIntrID = validateText(intrID);
		if (!chkIntrID)
			return false;
		else 
			return true;
			
	} else {
		var chkIntrIdentityNo = validateText(intrIdentityNo);
		if (!chkIntrIdentityNo && !chkIntrID)
			return false;
		else
			return true;
			
	}
} 

function validateDupID(memberID, intrID) {
	
	var temp1 = Trim(memberID.value);
	var temp2 = Trim(intrID.value);
	
	if (temp1 == temp2)
		return false;
	else 
		return true;
}

function validateDupIdentity(memberIdentityNo, intrIdentityNo) {
	
	var temp1 = Trim(memberIdentityNo.value);
	var temp2 = Trim(intrIdentityNo.value);
	
	if (temp1 == temp2)
		return false;
	else 
		return true;
}

function updateDob(vl, obj, country) {
	
  var vl = Trim(vl.value);
  
  if (country == 'MY') {
	  if (vl.length == 12) {
		  obj.value = vl.substring(4,6) +"-"+ vl.substring(2,4) +"-19"+ vl.substring(0,2);
	  }
  }
}	

/*============================================================================
 *  Address related
 ===========================================================================*/
 
function validateZipCode(obj) {

	var validCode = /\d{5}$/;
	
	var vl = TrimAll(obj.value);
	
	return validCode.test(vl);
}

/*============================================================================
 *  String related
 ===========================================================================*/

// Remove all spaces in an object value
function TrimObjValue(obj) {
  obj.value = Trim(obj.value);
}
  	  
// Remove all spaces to the right and left of a String
function Trim(str) {

  var res = /^\s+/ig;
  var ree = /\s+$/ig;
	
  var out = str.replace(res,"").replace(ree,"");
  return out;
}

// Removes all spaces in a String
function TrimAll(str) {
	
  var rem = /\s+/ig;
  var out = Trim(str);
	
  out = out.replace(rem, "");
  return out;
}

/*============================================================================
 *  Number related
 ===========================================================================*/
  
function isMoney(amt) {
	var x = 1;
	if (isNaN(amt)) {
		x = 0;
		return x;
	} else
		return x;
}

function isPositive(amt) {
	var x = 1;
	if (amt < 0) {
		x = 0;
		return x;
	}
	else
		return x;
}

function isZero(amt) {
	var x = 0;
	if (amt == 0) {
		x = 1;
		return x;
	} else
		return x;
}   

function isValueZero(amt) {
	if (amt.value == 0)
		return false;
	else
		return true;
}  
 
/*============================================================================
 *  Double related
 ===========================================================================*/
function validateDouble(obj) {
	
	var validId = /^([0-9|.]{0,30})$/i;

	var vl = obj.value;

	if (vl == "")
		return false;

	obj.value = vl;	
	return validId.test(vl);
}
 
/*============================================================================
 *  Date related
 ===========================================================================*/
   
var dtCh= "-";

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(obj){
	var dtStr = obj.value
	var msg = "Invalid date!"
	
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1) {
		focusAndSelect(obj);
    //alert(msg);
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		focusAndSelect(obj);
    //alert(msg);
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		focusAndSelect(obj);
    //alert(msg);
		return false
	}
	if (strYear.length != 4 || year==0){
		focusAndSelect(obj);
    //alert(msg);
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		focusAndSelect(obj);
    //alert(msg);
		return false
	}
	return true
}

/*============================================================================
 *  Control related
 ===========================================================================*/

function validateText(obj) {
	var temp_str = Trim(obj.value);
		
	if (temp_str == "") {
		obj.value = "";
		focusAndSelect(obj);
  	return false;
	} else {
		obj.value = temp_str;
		return true;
	}
}

function validateTextNoFocus(obj) {

	var temp_str = Trim(obj.value);
	
	if (temp_str == "") {
		obj.value = "";
  	return false;
	} else {
		obj.value = temp_str;
		return true;
	}
}

function validateObj(obj, compulsory) {

	if (getValueFromCtl(obj) == "" && compulsory=="1") {
		obj.focus();
		return false;
	} else {
		return true;
	}
}

function validateObjNoFocus(obj, compulsory) {

	if (getValueFromCtl(obj) == "" && compulsory=="1") {
		return false;
	} else {
		return true;
	}
}

function getValueFromCtl(obj) {
	for (var i=0; i < obj.options.length; i++) {		
		if (obj.options[i].selected ) {
			if (obj.options[i].value == "" || obj.options[i].value == "0" || obj.options[i].value == "-" || obj.options[i].value == "00" || obj.options[i].value == "000") {
				return "";
			} else
				return obj.options[i].value;
		}
	}
	
	return "";
}

function getSelectedRadio(buttonGroup) {
	// returns the array number of the selected radio button or -1 if no button is selected
	if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
	  for (var i=0; i<buttonGroup.length; i++) {
	     if (buttonGroup[i].checked) {
	        return i
	     }
	  }
	} else {
	  if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
	}
	// if we get to this point, no radio button is selected
	return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
	// returns the value of the selected radio button or "" if no button is selected
	var i = getSelectedRadio(buttonGroup);
	if (i == -1) {
	  return "";
	} else {
	  if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
	     return buttonGroup[i].value;
	  } else { // The button group is just the one button, and it is checked
	     return buttonGroup.value;
	  }
	}
} // Ends the "getSelectedRadioValue" function

function getSelectedCheckbox(buttonGroup) {
	// Go through all the check boxes. return an array of all the ones
	// that are selected (their position numbers). if no boxes were checked,
	// returned array will be empty (length will be zero)
	var retArr = new Array();
	var lastElement = 0;
	if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
	  for (var i=0; i<buttonGroup.length; i++) {
	     if (buttonGroup[i].checked) {
	        retArr.length = lastElement;
	        retArr[lastElement] = i;
	        lastElement++;
	     }
	  }
	} else { // There is only one check box (it's not an array)
	  if (buttonGroup.checked) { // if the one check box is checked
	     retArr.length = lastElement;
	     retArr[lastElement] = 0; // return zero as the only array value
	  }
	}
	return retArr;
} // Ends the "getSelectedCheckbox" function

function getSelectedCheckboxValue(buttonGroup) {
	// return an array of values selected in the check box group. if no boxes
	// were checked, returned array will be empty (length will be zero)
	var retArr = new Array(); // set up empty array for the return values
	var selectedItems = getSelectedCheckbox(buttonGroup);
	if (selectedItems.length != 0) { // if there was something selected
	  retArr.length = selectedItems.length;
	  for (var i=0; i<selectedItems.length; i++) {
	     if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
	        retArr[i] = buttonGroup[selectedItems[i]].value;
	     } else { // It's not an array (there's just one check box and it's selected)
	        retArr[i] = buttonGroup.value;// return that value
	     }
	  }
	}
	return retArr;
} // Ends the "getSelectedCheckBoxValue" function

function focusAndSelect(obj) {
  obj.focus();
  obj.select();
}

function loadCombobox(obj, selectedValue) {
	for (var i = 0; i < obj.length; i++) {
		if (obj.options[i].value == selectedValue){
			obj.options[i].selected = true;
			return;
		}
	}
}

function IsOn(oControl) {
	oControl.style.backgroundColor = "#ffffff";
}
	
function IsOff(oControl) {
	oControl.style.backgroundColor = "#ffffff";
}

// Kent added, 20080704. To handle null return 'object' type, which supposed to be 'null' or 'undefined'
function typeOf(value) {
	var s = typeof value;    
	if (s === 'object') {        
		if (value) {            
			if (value instanceof Array) {                
				s = 'array';            
			}        
		} else {            
			s = 'undefined'; //null  
		}    
	}    
	return s;
}
 
/*============================================================================
 *  Pop Up Window
 ===========================================================================*/

function popupSmall(link) {
  window.open(link , "", 'menubar=no,resizable=no,toolbar=no,scrollbars=yes,status=no,width=500,height=400,screenX=0,screenY=0');
}

function popupView(link, name) { //kent added, 20080603, to pass window.name
  window.open(link , name, 'menubar=no,resizable=yes,toolbar=no,scrollbars=yes,status=no,width=700,height=500,screenX=0,screenY=0');
}

function popupSubmit(link, name, form) { //kent added, 20080603, to pass window.name with form.submit() call

  var popup = window.open('', name+(new Date().getTime()), 'menubar=no,resizable=yes,toolbar=no,scrollbars=yes,status=no,width=700,height=500,screenX=0,screenY=0');
  
  form.action= link;
  form.target = popup.name;
  form.submit();
}

function popupViewDoc(link) {
  window.open(link , null, "menubar=no,resizable=yes,toolbar=no,scrollbars=yes,status=no,width=550,height=600,top=0,left=0");
}

function popupViewDoc(link, iWidth, iHeight) {
  window.open(link , "", "menubar=no,fullscreen=no,resizable=yes,toolbar=no,scrollbars=yes,status=no,width=" + iWidth + ",height=" + iHeight);
}

function popupViewSmallReceipt(link) {
  window.open(link , "", 'menubar=no,resizable=yes,toolbar=no,scrollbars=yes,status=no,width=300,height=600,screenX=0,screenY=0');
}

function popupHelpPage(sURL, iWidth, iHeight) {
	window.open(sURL,"Help","menubar=no,resizable=no,status=no,scrollbars=yes,width=" + iWidth + ",height=" + iHeight + ",location=no");
}

function popupViewImage(sURL, iWidth, iHeight) {
	window.open(sURL,"View","menubar=no,resizable=yes,status=no,scrollbars=yes,width=" + iWidth + ",height=" + iHeight + ",location=no");
}

function popupShopCart(link) {
  window.open(link , "CartPopup", 'menubar=no,resizable=no,toolbar=no,scrollbars=auto,status=no,width=220,height=300,screenX=0,screenY=0');
}

/*============================================================================
 *  Pop Up Image
 ===========================================================================*/

// Set the horizontal and vertical position for the popup
	
	PositionX = 100;
	PositionY = 100;
	
	// Set these value approximately 20 pixels greater than the
	// size of the largest image to be used (needed for Netscape)
	
	defaultWidth  = 500;
	defaultHeight = 500;
	
	// Set autoclose true to have the window close automatically
	// Set autoclose false to allow multiple popup windows
	
	var AutoClose = true;
	
	// Do not edit below this line...
	// ================================
	if (parseInt(navigator.appVersion.charAt(0))>=4){
	var isNN=(navigator.appName=="Netscape")?1:0;
	var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
	var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;
	function popImage(imageURL,imageTitle){
	if (isNN){imgWin=window.open('about:blank','',optNN);}
	if (isIE){imgWin=window.open('about:blank','',optIE);}
	with (imgWin.document){
	writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
	writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
	writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
	writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
	writeln('width=100-(document.body.clientWidth-document.images[0].width);');
	writeln('height=100-(document.body.clientHeight-document.images[0].height);');
	writeln('window.resizeTo(width,height);}');writeln('if (isNN){');       
	writeln('window.innerWidth=document.images["George"].width;');writeln('window.innerHeight=document.images["George"].height;}}');
	writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
	if (!AutoClose) writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
	else writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">');
	writeln('<img name="George" src='+imageURL+' style="display:block"></body></html>');
	close();		
	}}
	

	/*============================================================================
	 *  Window related
	 ===========================================================================*/
	
	
	function popupSmall(link) {
		window.open(link , '', 'menubr=no,resizable=no,toolbar=no,scrollbars=yes,status=no,width=500,height=400,screenX=0,screenY=0');
	}

	function popupViewMedium(link) {
		window.open(link , '', 'menubr=no,resizable=yes,toolbar=no,scrollbars=yes,status=no,width=550,height=600,screenX=0,screenY=0,location=no');
	}	