//  Function CheckTrading.js
//  Description : A set of JavaScript function to check trading input
//  Date		: Feb 25, 2000
// Author		: Sandy Chan
var msgEmpty = "Empty Input";
var msgIsNumber = "Not a valid number";
var errReduce = "E2119:Not a valid reduce quantity";

//**********************************************************
//Function	: parseStock
//Input		: String
//Output	: return a valid Stock value
//**********************************************************
function parseStock(str) {
	//search the string to see if it only contains characters
	var i;

	if (isNaN(str) || isEmpty(str))
		return str
	else
		return parseInt(str,10);
}//validEmail

//**********************************************************
//Function	: validEmail
//Input		: String
//Output	: True if the word contains only 1 '@' character
//**********************************************************
function validEmail(str) {
	//search the string to see if it only contains characters
	var i;
	var flag=false;
	var result=false;

	for (i=0; i < str.length; i ++) {
		var c = str.charAt(i);
			//if a non-character found
			if ((c == '@') && (flag == false)) {
				result = true;
				flag = true;
			}else if((c == '@') && (flag == true)){
				result = false;
			}
			//if
	}//for
	return result;
}//validEmail

//**********************************************************
// Function : isEmpty
// Input	: String
// Output	: True if only whitespace enters; otherwise, returns false
//**********************************************************
function isEmpty(str) {
var whitespace = " \t\n\r";
var i;
	//if no input
	if (( str==null) || (str.length==0)) return true;

	//search the string to see if non-whitespace characters enters
	for (i=0; i < str.length; i++) {
		var c = str.charAt(i);
		if (whitespace.indexOf(c) == -1)
			return false;
	}
	//all characters are whitespace
	return true;
}//isEmpty

//**********************************************************
//Function	: MsgAlert
//Input		: an alert message
//Output	: a message box to display the alert message
//**********************************************************
function MsgAlert(msg) {
	alert(msg);
}//MsgAlert


//**********************************************************
//Function	: isCharacter
//Input		: String
//Output	: True if the word contains only characters
//**********************************************************
function isCharacter(str) {
	//search the string to see if it only contains characters
	var i;
	for (i=0; i < str.length; i ++) {
		var c = str.charAt(i);
			//if a non-character found
			if (!(((c>= "a") && (c <= "z")) || (( c >= "A") && (c <= "Z")))) {
				return false;
			}//if
	}//for
	return true;
}//isCharacter


//**********************************************************
//Function	: isNumeric
//Input		: String
//Output	: True if the word contains only numbers
//**********************************************************
function isNumeric(str) {
	//search the string to see if it only contains numbers
	var i;
	for (i=0; i < str.length; i ++) {
		var c = str.charAt(i);
			//if a non-number found
			if ((c < '0') || ( c > '9')) {
		//	if (!((c >= '0') && (c <= '9'))) {
				return false;
			}//if
	}//for
	return true;
}//isNumeric

//**********************************************************
//Function	: checkDecimal
//Input		: String
//Output	: True if the word contains numbers or decimal
//**********************************************************
function checkDecimal(str) {
	//search the string to see if it only contains numbers
	var i;
	for (i=0; i < str.length; i ++) {
		var c = str.charAt(i);
			//if a non-number found
            if (((c < '0') || ( c > '9')) &&  ( c!='.')) {
				return false;
			}
	}
	return true;
}//checkDecimal




//**********************************************************
//Function	: checkQuantity
//Input		: String, Lot Size
//Output	: True if a correct quantity number entered
//**********************************************************
function checkQuantity(qty, lotsize) {
	//check if the input is valid numeric
	if (!isEmpty(qty)) {
	    if (!isNumeric(qty)) {
            alert("E2119:Invalid Quantity! Please input the Quantity in positive number.");
		    return false;
	    }
	    if (qty <= 0 ) {
		    alert("E2119:Invalid Quantity! Please input the Quantity in positive number.");
		    return false;
	    }


	    //check if quantity is valid
	    var result = Math.ceil(qty) % Math.ceil(lotsize);
	    if (result != 0 ) {
	        alert("E2119:Invalid Quantity! Please input a quantity in multiples of the Lot Size. Lot Size :" + lotsize);
		    return false;
	    }
	    return true;
    }
}//checkQuantity


//**********************************************************
//Function	: checkPrice
//Input		: String, Lot Size
//Output	: True if a correct lot price entered
//**********************************************************
function checkPrice(price, lotsize,type) {
	//check if the input is valid numeric
	if (!isEmpty(price)){
	    if (!checkDecimal(price)) {
		    alert("E2108:Invalid Order Price! Please input an Order Price in positive number.");
		    return false;
	    }//if

    	//check if price is 4 decimal numbers
    	//(price >= 0.0 && Math.ceil(price * 10000.0)/(double)10000.0 == price)
	   result = Math.round(price * 10000)/10000;
	   //alert( result  + price);

	   if (isNaN(result) || result <= 0) {
		    alert("E2109:Invalid Price! Please input the Price in positive number.");
		    return false;
	    }else  if (parseFloat(result) != parseFloat(price)) {
		   alert("E2107:Invalid Order Price! Please input an Order Price with no more than 4 decimal places.");
		    return false;
	    }//if

	    return true;
    }
}//checkPrice


//**********************************************************
//Function	: checkStockCode
//Input		: String
//Output	: True if it is a valid character or number
//**********************************************************
 function checkStockCode(stockcode) {
 		//alert(stockcode);
	if (isEmpty(stockcode)) {
		//alert("Please enter stock code");
		alert("E2113:Stock code is missing! Please enter a stock code.");
		return false;
	}
	if (!isNumeric(stockcode) && !isCharacter(stockcode)) {
		//alert("Invalid stock code. Please enter valid stock code");
		alert("E2122:Invlid stock code! Please enter the stock code again.");
		return false;
	}


	return true;

}//checkStockCode


//**********************************************************
//Function	: checkReduceQty
//Input		: Current value, Old value
//Output	: True if a correct quantity number entered
//			  remain amount must be greater than 0
//**********************************************************
function checkReduceQty(oldqty, newqty, execqty, lotSize) {
	if (!isNumeric(String(oldqty)) || !isNumeric(String(newqty))) {
		//alert("Invalid Reduce quantity input. Quantity must be numbers only");
		alert("E2119:Invalid Quantity! Please input the Quantity in positive number.");
		return false;
	}

	execqty = execqty * 1;
	newqty = newqty * 1;
	oldqty = oldqty * 1;
	lotSize = lotSize * 1;

    var rule1 = (execqty > 0 && newqty >= execqty && newqty < oldqty && (newqty % lotSize) == 0);
    var rule2 = (execqty == 0 && newqty > execqty && newqty < oldqty && (newqty % lotSize) == 0);

    if (rule1 == false && rule2 == false) {
        alert("E2119:Invalid reduce quantity");
        document.confirmForm.REDUCE_QTY.focus();
        return false;
    }

	document.confirmForm.newOSQty.value = newqty - execqty;

	return true;
}//checkReduceQty

//**********************************************************
//Function	: checkPassword
//Input		: trading password, name of Order (eg. "Reduce Order")
//Output	: True if user remebers to input trading password
//**********************************************************
function checkPassword(str) {
	if (isEmpty(str)) {
		alert("E2135:Trading Password is missing! Please enter your Trading Password again to confirm your order.");
        return false;
 }else {
	    return true;
 }
}

//**********************************************************
//Function	: checkOrder
//**********************************************************

function checkOrder(qty, price, lotsize) {
      return (checkQuantity(qty, lotsize) && checkPrice(price, lotsize,"board lot"));
}
//**********************************************************
//Function	: checkRadio
//**********************************************************

function checkRadio(buyobj, sellobj, priceobj, qtyobj,  oddprice,oddqty, lotsize, index) {
   if ((buyobj.checked ) || (sellobj.checked)) {
        if (isEmpty(qtyobj.value) && isEmpty(priceobj.value) && isEmpty(oddqty.value) && isEmpty(oddprice.value)){
           alert("E2124:Invalid Order instruction! Please enter the order quantity and price.");
           return false;
        }

        if ((isEmpty(qtyobj.value) && !isEmpty(priceobj.value))) {
          alert("E2106:Board Lot order Quantity is missing! Please input your order quantity.");
          return false;
        }
        if (!isEmpty(qtyobj.value) && isEmpty(priceobj.value)) {
          alert("E2107:Board Lot order price is missing! Please input your order price.");
          return false;
        }

        if (index !=0) {
           if ((isEmpty(oddqty.value) && !isEmpty(oddprice.value))) {
               alert("E2110:Odd Lot order quantity is missing! Please input your order quantity.");
               return false;
           }
           if (!isEmpty(oddqty.value) && isEmpty(oddprice.value)) {
               alert("E2109:Odd Lot order price is missing! Please input your order price.");
               return false;
           }
        }
        if (!isEmpty(qtyobj.value) && !isEmpty(priceobj.value)) {
            if (!checkOrder(qtyobj.value, priceobj.value, lotsize.value)) {
               // alert("Invalid Board Lot quantity! Please input the Quantity in positive number.");
                return false;
            }
        }

        if (!isEmpty(oddqty.value) && (index == 0 || !isEmpty(oddprice.value))) {
            if (!isNumeric(oddqty.value) || Number(oddqty.value) <= 0) {
                alert("E2108:Invalid Odd Lot quantity! Please input a positive Odd Lot quantity!");
                return false;
            }
            
            if (Number(oddqty.value) >= Number(lotsize.value)) {
                alert("E2109:Invalid Odd Lot quantity! The odd lot quantity cannot be the same or greater than one lot size!");
                return false;
            }

            if (index != 0) {
                return checkPrice(oddprice.value, lotsize.value,"odd lot");
            }
        }

   }else {
         MsgAlert("E2105:No Buy/Sell instruction! Please select the Buy or Sell button.");
        return false;
  }


   return true;



}//checkRadio

function isValidDate(vYear, vMonth, vDay)
{
    var year = Number(vYear);
    var month = Number(vMonth);
    var day = Number(vDay);

//    alert("original year "+vYear+" month "+vMonth+" day "+vDay);

//    alert("year "+year+" month "+month+" day "+day);
    if (isNaN(year) || isNaN(month) || isNaN(day))
    {
        return false;
    }

    if (year < 1900 || month < 1 || month > 12 || day < 1 || day > 31)
    {
        return false;
    }

    if (day == 31 && (month == 4 || month == 6 || month == 9 || month == 11))
    {
        return false;
    }

    if (month == 2)
    {
        if (((year % 4) == 0 && (year % 100) != 0) || year % 400 == 0) // leap year
        {
            if (day > 29)
            {
                return false;
            }
        }
        else
        {
            if (day > 28)
            {
                return false;
            }
        }
    }

    return true;
}

// Login/Trading password cannot be null and the length must between 6-10
function checkPasswordLength(password, lower, upper) {
  var lBound = 8;
  var uBound = 10;
  if (lower) lBound = lower;
  if (uBound) uBound = upper;
  
  if (password.length < lBound || password.length >uBound) {
    return false;
  }
  return true;
}


// New password must be different from the old password.
function checkPasswordDiff(oldPassword, newPassword) {
  if (oldPassword == newPassword) {
	return false;
  }
  return true;
}

// If pw is numeric, it cannot be in all sequencial ascending or descending order
// check isNumeric() first!

function checkNumPasswordSeq(password) {

  var ind1 = 1;
  var ind2 = 1;


  for (i=0; i < password.length-1; i++) {
  	var followNum = i+1;
    if (password.substring(i, followNum) != (password.substring(followNum, followNum +1) - 1)) {
      ind1 = 0;
    }

    if ((password.substring(i, followNum)-1) != password.substring(followNum, followNum +1)) {
      ind2 = 0;
    }

  }

  if (ind1 == 0 && ind2 ==0) {
    return true;
  } else {

    return false;
  }

}

// The password cannot be  all of the same number or letter
function checkPasswordCharacter(password) {

  var ind = 1;
  for (i=0; i < password.length; i++) {
  	  var followINum = i+1;

      for (j=0; j < password.length; j++) {
      	var followJNum = j+1;

        if (password.substring(i, followINum) != password.substring(j, followJNum)) {
          ind = 0;
        }
      }

  }

  if (ind == 0) {
    return true;
  } else {

    return false;
  }
}

String.prototype.trim = function() {

// skip leading and trailing whitespace
// and return everything in between
  return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");

}

function showOverdueWin(a) {
	remote = window.open("", "overdue", "menubar=yes, scrollbars=yes, resizable=yes, width=600, height=250,alwaysRaised=yes,left=0,top=0,screenX=0,screenY=0");

	if (remote.opener == null) {
		remote.opener = window;
	} else {
		remote.focus();
	}

	remote.document.open();
	remote.document.write("<html><title>338.Net -- Call Overdue</title>");
	remote.document.write("<meta http-equiv='Content-Type' content='text/html; charset=big5'>");
	remote.document.write("<link rel=stylesheet href='/its/default.css' type='text/css'>");
	remote.document.write("<BODY bgColor=#ffffff leftMargin=0 topMargin=0 marginheight='0' marginwidth='0'>" +
	"<table width='580' border='0' cellspacing='0' cellpadding='0' background='/its/images/header/top_bg.gif'>" +
	"<tr background='/its/images/header/top_bg.gif'> <td height='64' valign='bottom' width='608'> " +
	"<table width='177' border='0' cellspacing='0' cellpadding='0' background='/its/images/header/logo_bg.gif'> " +
	"<tr valign='bottom' background='/its/images/header/logo_bg.gif'> <td rowspan='2' width='5'>" +
	"<br> <img src='/its/images/header/top_bg02.gif' width='5' height='7'></td> " +
	"<td width='165'><img src='/its/images/header/new_logo.gif' width='160' height='50'><br> </td> " +
	"<td rowspan='2' width='7'><img src='/its/images/header/top_image01.gif' width='7' height='12'></td> </tr> " +
	"<tr> <td width='165'><img src='/its/images/header/top_bg02.gif' width='165' height='7'></td> </tr> " +
	"</table> </td> " +
	"<td height='64' valign='top' width='172' align=right> <br> </td> </tr> </table> ");
	remote.document.write("<table width=580><tr><td align=center><table><tr><td><br><b><font color=red>Your Account Is Now Overdue.</font><br>Immediate Settlement of $");
	remote.document.write(a);
	remote.document.write(" In Full Before Buy Orders Can Be Placed.</b><br><br>Click here for <a href=# onclick=\"javascript:opener.location.href ='https://www.trade.338.net/cgi-bin/gx.cgi/AppLogic+its.CashPositionSummary?CURRENCY=HKD';window.close();\">Cash Position.</a>");
	remote.document.write("<br><br><input type=button name=cl value='Close' onClick='window.close();'></td></tr></table></td></tr></table></body></html>");
}



