// $Id: utils.js,v 1.7.2.1 2007/07/12 16:42:42 aukeith Exp $

// define a global variable for checking the submit twice problem
var _g_isAlreadySubmitted = false;

function removeSelectedOptions(obj){
  for(var i=(from.options.length-1);i>=0;i--){
    var o=obj.options[i];
      if(o.selected){
        from.options[i] = null;
      }
    }
  from.selectedIndex = -1;
}

function selectAllOptions(obj){
  for(var i=0;i<obj.options.length;i++){
    obj.options[i].selected = true;
  }
}

function clearOptions(obj, keepItemIndex) {
  if (obj != undefined && obj.options.length > keepItemIndex) {
    for(i=obj.options.length-1;i>keepItemIndex;i--){
      obj.options[i] = null;
      obj.selectedIndex = -1;
    }
  }
}

/*
  does not work if passed in document.getElementById("obj")
  should pass in document.formName.obj instead
*/
function getRadioValue(obj) {
  for (i = 0; i < obj.length; i++) {
    if (obj[i].checked) {
    return obj[i].value;
    }
  }
  return '';
}

function setRadioValue(obj, val) {
  for (i = 0; i < obj.length; i++) {
    if (obj[i].value == val) {
      obj[i].checked = true;
      break;
    }
  }
}

function setRadioDisable(obj) {
  for (i = 0; i < obj.length; i++) {
    obj[i].disabled=true
    }
}
function setRadioEnable(obj) {
  for (i = 0; i < obj.length; i++) {
    obj[i].disabled=false
    }
}

function setComboItem(combo, val) {
  for (i = 0; i < combo.length; i++) {
    if (combo[i].value == val) {
      combo[i].selected = true;
    }
  }
}

function toggleSelectAll(thisCheckbox, checkboxItem) {
  var isChecked = thisCheckbox.checked;
  if ((typeof checkboxItem) != 'undefined')
  {
    if ((typeof checkboxItem.length) != 'undefined') {
      for (var i = 0; i < checkboxItem.length; i++) {
        if (!checkboxItem[i].disabled) {
          checkboxItem[i].checked = isChecked;
        }
      }
    }
    else {
      if (!checkboxItem.disabled) {
        checkboxItem.checked = isChecked;
      }
    }
  }
}

function isSelected(checkboxItem)
{
  if ((typeof checkboxItem) != 'undefined') {
    if ((typeof checkboxItem.length) != 'undefined') {
      for (var i = 0; i < checkboxItem.length; i++) {
        if (checkboxItem[i].checked == true) {
          return true;
        }
      }
    }
    else {
      if (checkboxItem.checked == true) {
        return true;
      }
    }
  }
  return false;
}

function getComboValue(combo) {
  for (i = 0; i < combo.length; i++) {
    if (combo[i].selected) {
      return combo[i].value;
    }
  }
  return;
}

function format(num, decimal) {
  var tmpNum = new NumberFormat(num);
  tmpNum.setCurrency(false);
  tmpNum.setCommas(false);
  tmpNum.setPlaces(decimal);
  return tmpNum.toFormatted();
}

function formatComma(num, decimal) {
  var tmpNum = new NumberFormat(num);
  tmpNum.setCurrency(false);
  tmpNum.setCommas(true);
  tmpNum.setPlaces(decimal);
  return tmpNum.toFormatted();
}

/**
 * Return the age of the input birthday (vs today).
 * @param year year of birthday
 * @param month month of birthday
 * @param day day of birthday
 */
function getAge(year, month, day) {
  var today = currentDate; // use current date object defined in header.jsp
  if (isNaN(month)) {
    month = today.getMonth() + 1;
    day = today.getDate();
  }
  if (isNaN(day)) {
    day = today.getDate();
  }
  return getAgeDiff(year, month, day, today.getFullYear(), today.getMonth() + 1, today.getDate());
}

/**
 * Return the age of the input birthday (vs a specified day).
 * @param fromYear year of birthday
 * @param fromMonth month of birthday
 * @param fromDay day of birthday
 * @param toYear year of date to compare
 * @param toMonth month of date to compare
 * @param toDay day of date to compare
 */
function getAgeDiff(fromYear, fromMonth, fromDay, toYear, toMonth, toDay) {
  //alert(fromYear + '.' + fromMonth + '.' + fromDay + '.' + toYear + '.' + toMonth + '.' + toDay);
  var fYear = parseInt10(fromYear);
  var fMonth = parseInt10(fromMonth - 1);
  var fDay = parseInt10(fromDay);
  var tYear = parseInt10(toYear);
  var tMonth = parseInt10(toMonth - 1);
  var tDay = parseInt10(toDay);
  //alert(fYear + '.' + fMonth + '.' + fDay + '.' + tYear + '.' + tMonth + '.' + tDay);

  var fromDate = new Date(fYear, fMonth, fDay);
  var toDate = new Date(tYear, tMonth, tDay);

  if (isNaN(fromDate) || isNaN(toDate)) {
    return 0;
  }

  var age = tYear - fYear;
  if (age <= 0) {
    return 0;
  }

  if (tMonth < fMonth) {
    return --age;
  }

  if ((tMonth == fMonth) && (tDay < fDay)) {
    return --age;
  }

  return age;
}

function parseInt10(str) {
  return parseInt(str, 10);
}

function checkHkId(idType, idText) {
  if (idType != "01") {
    return true;
  }
  if (idText == null || idText.length == 0) {
    return false;
  }
  var valid = "abcdefghijklmnopqrstuvwxyz0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  for (i = 0; i < idText.length; i++) {
    subChar = idText.charAt(i);
    if (valid.indexOf(subChar) == -1) {
      return false;
    }
  }
  return true;
}

/* internal use */
function _openPopupWin(url,name) {
  // FC Modify Start: for Firefox compliances
  // if the target window happens to be the current window, use 'self.location.href' instead of 'window.open',
  // so that in firefox, window.opener can return the actual parent window.
  /*
  var newwin = window.open(url,name,'left=47,top=10,width=930,height=660,scrollbars=yes,status=yes,resizable=yes');
  if (newwin) {
    newwin.focus();
    newwin.moveTo(47,10);
  }
  */
  if (name != null && name != '' && self.name == name) {
    self.location.href = url;
    self.focus();
    self.moveTo(47,10);
  } else {
    var newwin = window.open(url,name,'left=47,top=10,width=930,height=660,scrollbars=yes,status=yes,resizable=yes');
    if (newwin) {
      newwin.focus();
      try {
        newwin.moveTo(47,10);
      } catch(ex) {
        // Ignore permission denied error:
        // Permission denied error occurs if the popup content is from a different domain
      }
    }
  }
  // FC Modify End: for Firefox compliances
}

function popupPrintable(url) {
  var newwin = window.open(url,'com_etnetsi_wms_printable_popup','left=47,top=10,width=700,height=660,scrollbars=yes,status=yes,resizable=yes');
  if (newwin) {
    newwin.focus();
    newwin.moveTo(47,10);
  }
}

function popupNewsPrintable(url) {
  var newwin = window.open(url,'com_etnetsi_wms_printable_popup','left=47,top=10,width=800,height=660,scrollbars=yes,status=yes,resizable=yes');
  if (newwin) {
    newwin.focus();
    newwin.moveTo(47,10);
  }
}

function popupNews(domain, newsId, refNo, duration) {
  var url =
    "market.searchMarketNews.do?duration=" + duration
      + "&newsDomain=" + domain
      + "&newsId=" + newsId
      + "&newsRefNo=" + refNo;
  window.name = "newsMainWindow";
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function popupTopNews(domain, newsId, refNo, duration) {
  var url =
    "market.searchMarketTopNews.do?duration=" + duration
      + "&newsDomain=" + domain
      + "&newsId=" + newsId
      + "&newsRefNo=" + refNo;
  window.name = "newsMainWindow";
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function popupMessage(url) {
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function marketDataPopup(url) {
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

/**
 * use another name as the window name because this function may be called in pop up window
 */
function popupAttachment(url) {
  _openPopupWin(url,'');
}

function popupSelectStaff(url){
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function popupReport(url){
  _openPopupWin(url,'');
}

function popupDocument(url){
  _openPopupWin(url,'');
}

function popupNewProduct(url) {
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function popupChildWin(url){
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function win_pop(url,wi,he,x,y) {
  newwin = window.open(url,'com_etnetsi_wms_popup','maximize=no,resizable=no,menubar=yes,toolbar=yes,scrollbars=yes,status=no,width=' + wi + ',height=' + he + ',left=' + x + ',top=' + y);
  if (newwin) {
    newwin.focus();
  }
}

function popupHelp(url){
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function popupMarketNews(url){
  _openPopupWin(url,'com_etnetsi_wms_popup');
}

function popupManual(url){
  _openPopupWin(url,'com_etnetsi_wms_popup_child');
}

/**
 * Synchronize all drop down lists to select the same item.
 * @param obj the array object of the combo box
 * @param index the selected index
 */
function syncDropDownList(obj,index){
  for (i=0;i<obj.length;i++){
    obj[i][index].selected = true;
  }
}

function syncTextBox(obj,value){
  for (i=0;i<obj.length;i++){
    obj[i].value = value;
  }
}

/**
 * Remove leading blanks from our string.
 * @param str the string we want to LTrim
 */
function lTrim(str) {
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...
      var j=0, i = s.length;
      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(j, i);
   }
   return s;
}

/**
 * Remove trailing blanks from our string.
 * @param str the string we want to RTrim
 */
function rTrim(str) {
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...
      var i = s.length - 1;       // Get length of string
      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, i+1);
   }
   return s;
}

/**
 * Remove trailing and leading blanks from our string.
 * @param str the string we want to Trim
 */
function trim(str) {
   return rTrim(lTrim(str));
}

function isNumberFormat(strBeCheck) {
  if (strBeCheck.length == 0) {
    return false;
  }
  if (strBeCheck.charAt(0) == ".") {
    return false;
  }

  var strCheck = "0123456789.";
  for (i = 0;  i < strBeCheck.length;  i++) {
    var hasPoint = false;
    ch = strBeCheck.charAt(i);
    if (ch == ".") {
      if (hasPoint) {
        return false;
      }
      else {
      hasPoint = true;
      }
    }
    for (j = 0;  j < strCheck.length; j++) {
      if (ch == strCheck.charAt(j)) {
        break;
      }
    }
    if (j == strCheck.length) {
      return false;
    }
  }

  return true;
}

function marketAddToBasket(url) {
  top.opener.location.href = url;
  window.close();
  return true;
}

//FC Add Start: Add the items to the popup window
function marketAddToBasketToPopup(url) {
  self.location.href = url;
  return true;
}
//FC Add End: Add the items to the popup window

/**
 *@param numStr , String type , make ensure it's a valid float number
 *@param noOfDec, Integer type, number of Decimal of the float number, make sure it's > 0
 *
 *@return true if numStr has noOfDec or less decimal place
 *
 */
function checkDecimalFormat(numStr, noOfDec){
  if (numStr.indexOf(".") != -1){
    var decimal = numStr.substring(numStr.indexOf(".")+1);
    while (decimal.length > noOfDec){
      if (decimal.charAt(decimal.length-1) == '0'){
        decimal = decimal.substring(0,decimal.length-1);
      }
      else {
        break;
      }
    }
    if (decimal.length > noOfDec){
      return false;
    }
  }
  return true;
}

function toHex(integer) {
  hexValues = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
  hexDigit1 = Math.floor(integer / 16);
  hexDigit2 = (integer % 16);
  return hexValues[hexDigit1] + hexValues[hexDigit2];
}

function encodeUtf8Url(str) {
  var utf8Str = encodeUtf8Text(str);
  var utf8Url ="";
  for(var n = 0; n < utf8Str.length; n++) {
    utf8Url += '%' + toHex(utf8Str.charCodeAt(n));
  }
  return utf8Url;
}

// this is copy from http://selfaktuell.teamone.de/artikel/javascript/utf8b64/utf8.htm,
// the orginal name of this function is encode_utf8()
function encodeUtf8Text(rohtext) {
  // dient der Normalisierung des Zeilenumbruchs
  rohtext = rohtext.replace(/\r\n/g,"\n");
  var utftext = "";
  for(var n=0; n<rohtext.length; n++) {
    // ermitteln des Unicodes des  aktuellen Zeichens
    var c=rohtext.charCodeAt(n);
    // alle Zeichen von 0-127 => 1byte
    if (c<128) {
      utftext += String.fromCharCode(c);
    }
    // alle Zeichen von 127 bis 2047 => 2byte
    else if((c>127) && (c<2048)) {
      utftext += String.fromCharCode((c>>6)|192);
      utftext += String.fromCharCode((c&63)|128);
    }
    // alle Zeichen von 2048 bis 66536 => 3byte
    else {
      utftext += String.fromCharCode((c>>12)|224);
      utftext += String.fromCharCode(((c>>6)&63)|128);
      utftext += String.fromCharCode((c&63)|128);}
    }
  return utftext;
}

// this function is used to get the offsetTop of the element
// i.e. the distance from the top of the window to the offset of the element
function getOffsetTop(obj) {
  var objParent = obj.offsetParent;
  objOffsetTop = obj.offsetTop;
  while (objParent != null) {
    objOffsetTop += objParent.offsetTop;
    objParent = objParent.offsetParent;
  }
  return objOffsetTop;
}

// this function is used to get the offsetLeft of the element
// i.e. the distance from the left of the window to the offset of the element
function getOffsetLeft(obj) {
  var objParent = obj.offsetParent;
  objOffsetLeft = obj.offsetLeft;
  while (objParent != null) {
    objOffsetLeft += objParent.offsetLeft;
    objParent = objParent.offsetParent;
  }
  return objOffsetLeft;
}

function logAccess(method) {
  var srcPath = 'log.access.do?method=' + method;
  var innerHTML = '<IFRAME id="logAccess" src="' + method + '" style="position:absolute;visibility:hidden;top:0px:left:0px;height:0px;width:0px;z-index:10" height="0" width="0" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></IFRAME>';
  var logObj = document.getElementById('logAccess');
  if (logObj == null || logObj == 'undefined') {
    var newLogLayer = document.getElementById('logAccessLayer');
    if (newLogLayer == null || newLogLayer == 'undefined') {
      newLogLayer = document.createElement('div');
      newLogLayer.setAttribute('id', 'logAccessLayer');
      newLogLayer.setAttribute('style', 'position:absolute;visibility:hidden;top:0px:left:0px;height:0px;width:0px;z-index:10');
      document.body.appendChild(newLogLayer);
    }
    newLogLayer.innerHTML = innerHTML;
    logObj = document.getElementById('logAccess');

  }
  logObj.src=srcPath;
}

// FC add start: functions for cookie handling
function writeCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

function readCookie(name) {
  var fullCookieStrArray = document.cookie.split("; ");
  for (var i = 0; i < fullCookieStrArray.length; i++) {
    var cookieStrArray = fullCookieStrArray[i].split("=");
    if (unescape(cookieStrArray[0]) == name) {
      if(!cookieStrArray[1]) {
        return null;
      }
      else {
        return unescape(cookieStrArray[1]);
      }
    }
  }
  return null;
}

function eraseCookie(name) {
	writeCookie(name,"",-1);
}

function isCookieEnabled() {  
    writeCookie("dummy", "dummy", null);

    var tmpCookie = readCookie("dummy");
    if (tmpCookie != null) {
       eraseCookie("dummy");
       return true; 
    }
    return false;
  }

// FC add end: functions for cookie handling
