// TFG javascripts

// Generic variables
var nwin	= null;
var TFGFollowPopup = null;

// Min/max
var ImagePlus	= '<IMG SRC=/pictures/main-nav-plus.gif WIDTH=12 HEIGHT=12 ALIGN=left BORDER=0>';
var ImageMinus	= '<IMG SRC=/pictures/main-nav-minus.gif WIDTH=12 HEIGHT=12 ALIGN=left BORDER=0>';

// Variable object declarations
function MinMaxString() {
  this.min = '';
  this.max = '';
}

MinMaxString.prototype.update = function( nStr ) {
  t = nStr.split(";#;");

  // If it is single entry: just update the max string
  if ( t[1] ) {
    this.min = t[0];
    this.max = t[1];
  }
  else {
    this.max = t[0];
  }
}

// Variable object declarations
function TFGActiveContent() {
  this.val = '';
}

TFGActiveContent.prototype.update = function( nStr ) {
  this.val = nStr;
}

function show_newwindow(wname) {
  var wwid = 640;
  var whei = 480;

  if (nwin == null || nwin.closed) {
    nwin = window.open(wname,"TFG_NEWWINDOW","menubar=yes,location=yes,scrollbars=yes,resizable=yes,width="+wwid+",height="+whei);
  }
  else {
    window.nwin.location=wname;
  }

  nwin.focus();
}

// TFG css popup: show
function show_mproduct_popup( PopWidth, PopData, fButton ) {
  var mycurtain = document.getElementById( "bodycurtain" );
  var mybox = document.getElementById( "maindialog" );
  var myboxbutton = document.getElementById( "myboxbutton" );
  var popupObj  = document.getElementById("maindialogcontent");

  mycurtain.style.height = document.body.clientHeight  + "px";
  mybox.style.width  = PopWidth  + "px";
  mybox.style.left = ((document.body.clientWidth - PopWidth) / 2) + "px";
  myscrolltop = (self.pageYOffset) ? self.pageYOffset :
                (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop :
                document.body.scrollTop;
  mybox.style.top = 200 + myscrolltop + "px";
  popupObj.innerHTML = PopData;

  document.body.scroll = "no";
  mycurtain.style.display = "block";
  mybox.style.display = "block";

  if ( fButton ) { myboxbutton.style.display = "block"; }
  else { myboxbutton.style.display = "none"; }
}

// TFG css popup: hide
function hide_mproduct_popup( ) {
  var mycurtain = document.getElementById( "bodycurtain" );
  var mybox = document.getElementById( "maindialog" );

  mycurtain.style.display = "none";
  myboxbutton.style.display = "none";
  mybox.style.display = "none";
  document.body.scroll = "yes";

  /* If there is a follow up function, execute it */
  if ( TFGFollowPopup ) { eval( TFGFollowPopup ); }
}

function mainShowMinDiv( aDivID ) {
  var minObj = document.getElementById( aDivID + 'Min' );
  var maxObj = document.getElementById( aDivID + 'Max' );

  minObj.style.display = "block";
  maxObj.style.display = "none";
}

function mainShowMaxDiv( aDivID ) {
  var minObj = document.getElementById( aDivID + 'Min' );
  var maxObj = document.getElementById( aDivID + 'Max' );

  minObj.style.display = "none";
  maxObj.style.display = "block";
}

function mainShowMinContent( aDivID, aVar ) {
  var targetObj = document.getElementById( aDivID );
  targetObj.innerHTML = '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=2 WIDTH="100%"><TR><TD WIDTH=18 VALIGN=top><A HREF="javascript:mainShowMaxContent(\''
		+ aDivID + '\', HTML' + aDivID + ' );">' + ImagePlus + '</A></TD><TD>'
                + aVar.min + '</TD></TR></TABLE>';
}

function mainShowMaxContent( aDivID, aVar ) {
  var targetObj = document.getElementById( aDivID );
  targetObj.innerHTML = '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=2 WIDTH="100%"><TR><TD WIDTH=18 VALIGN=top><A HREF="javascript:mainShowMinContent(\''
		+ aDivID + '\', HTML' + aDivID + ' );">' + ImageMinus + '</A></TD><TD>'
                + aVar.max + '</TD></TR></TABLE>';
}

function mainShowActiveContent( aDivID, aVar ) {
  var targetObj = document.getElementById( aDivID );
  targetObj.innerHTML = aVar.val;
}

// Ajax submit: form
function mainSubmitAjaxForm( aURL, aFormID, rVar, fDiv, rURL, TailChain, URLstradd ) {
  var ajaxObj = new sack();
  var aForm = document.getElementById( aFormID );

  if ( ! rURL ) { rURL = window.location.href; }

  // Fill the form variables
  for(i=0; i< aForm.elements.length; i++) {
    if ( aForm.elements[i].type == "select-multiple" ) {
      for( j=0; j< aForm.elements[i].options.length; j++ ) {
        if ( aForm.elements[i].options[j].selected ) {
          if ( ajaxObj.URLString ) { ajaxObj.URLString += "&"; }
          ajaxObj.URLString += encodeURI(aForm.elements[i].name) + "=" + encodeURI(aForm.elements[i].options[j].value);
        }
      }
    }
    else if ( aForm.elements[i].type == "checkbox" ) {
      if ( aForm.elements[i].checked ) {
        if ( ajaxObj.URLString ) { ajaxObj.URLString += "&"; }
        ajaxObj.URLString += aForm.elements[i].name + "=" + encodeURI(aForm.elements[i].value);
      }
    }
    else {
      if ( ajaxObj.URLString ) { ajaxObj.URLString += "&"; }
      ajaxObj.URLString += aForm.elements[i].name + "=" + encodeURI(aForm.elements[i].value);
    }
  }

  // Add additional data
  if ( URLstradd ) {
    if ( ajaxObj.URLString ) { ajaxObj.URLString += "&"; }
    ajaxObj.URLString += URLstradd;
  }

  ajaxObj.requestFile = aURL;
  ajaxObj.onCompletion = function(){
	if ( ajaxObj.response == 1 ) {
	  eval(TailChain);
	  TFGFollowPopup = "window.location.href='" + rURL + "';";
	  show_mproduct_popup(360, '<DIV STYLE="color: green; font-weight: bold; text-align: center; margin-top: 5px; margin-bottom: 5px;">Your request is successfully submitted. Reloading page...</DIV>', false);
	  // Auto load
	  setTimeout( "window.location.href='" + rURL + "';", 500);
	}
	else {
	  if ( fDiv ) {
  	    var rDiv = document.getElementById( rVar );
	    rDiv.innerHTML = ajaxObj.response;
            // Execute javascript
            var re = /<script\b.*?>([\s\S]*?)<\/script/ig; 
            var match;
            while (match = re.exec(rDiv.innerHTML)) { eval(match[1]); }
	  }
	  else { rVar.update( ajaxObj.response ); }
	  eval(TailChain);
	}
  };
  ajaxObj.runAJAX();
}

// Ajax submit: simple
function mainSubmitAjaxSimple( aURL, cbURL, URLstradd ) {
  var ajaxObj = new sack();

  // Form first visit
  fname = "first_visit";
  ajaxObj.URLString = fname + "=no";

  // Add additional data
  if ( URLstradd ) {
    if ( ajaxObj.URLString ) { ajaxObj.URLString += "&"; }
    ajaxObj.URLString += URLstradd;
  }

  ajaxObj.requestFile = aURL;
  ajaxObj.onCompletion = function(){ 
	if ( ajaxObj.response == 1 ) {
	  TFGFollowPopup = "window.location.href='" + cbURL + "';";
	  show_mproduct_popup(360, '<DIV STYLE="color: green; font-weight: bold; text-align: center; margin-top: 5px; margin-bottom: 5px;">Your request is successfully submitted. Reloading page...</DIV>', false);
	  // Auto load
	  setTimeout( "window.location.href='" + cbURL + "';", 500);
	}
	else {
	  show_mproduct_popup(360, '<DIV STYLE="color: green; font-weight: bold; text-align: center; margin-top: 5px; margin-bottom: 5px;">' + ajaxObj.response + '</DIV>', true);
	}
  };
  ajaxObj.runAJAX();
}

function mainAddNewAddress( aBox, companyID ) {
  addrID = aBox[aBox.selectedIndex].value;

  // Address
  if ( addrID == 1 ) {
    show_mproduct_popup(720, '<DIV ID="newAddrFormText"> </DIV>', false);
    mainShowActiveContent( 'newAddrFormText', HTMLnewAddrFormText );
  }
}

function mainFormFillSelect( aBox, URLpre, sBoxName ) {
  var ajaxObj = new sack();
  var sBoxList = document.getElementsByName(sBoxName);
  var compID = aBox[aBox.selectedIndex].value;
  // Object
  var sBox = sBoxList[0];

  // Company
  if ( compID ) {
    ajaxObj.requestFile = URLpre + compID;
    ajaxObj.onCompletion = function(){
      /* Clear the list */
      for(i=sBox.options.length; i >= 0; --i ) { sBox.options[i] = null; }

      var sStr = ajaxObj.response.split(";");
      for( i=0; i < sStr.length; i++ ) {
        if ( sStr[i] ) {
          sStrDetail = sStr[i].split("#");
          nIndex = sBox.options.length;
          sBox.options[nIndex] = new Option( sStrDetail[1] , sStrDetail[0] );
         }
      }

      /* Reset the selected one */
      sBox.selectedIndex = 0;
    };

    ajaxObj.runAJAX();
  }
  else {
    /* Clear the list */
    for(i=sBox.options.length; i >= 0; --i ) { sBox.options[i] = null; }
  }
}

function mainFormFillbSelect( aBoxName, URLpre, bBoxName ) {
  var ajaxObj = new sack();
  var i, dVal;

  dVal = 0;
  for(i=1; i < 16; i++) {
    aBoxObj = document.getElementById(aBoxName + i);
    if ( ! aBoxObj ) { break; }
    if ( aBoxObj.checked ) { dVal += Math.pow(2,i); }
  }

  eVal = 0;
  for(i=1; i < 64; i++) {
    bBoxObj = document.getElementById(bBoxName + i);
    if ( ! bBoxObj ) { break; }
    if ( bBoxObj.checked ) { eVal += Math.pow(2,i); }
  }

  ajaxObj.requestFile = URLpre + dVal + "/" + bBoxName + "/" + eVal;
  ajaxObj.onCompletion = function(){
    var bBoxDiv = document.getElementById("div_" + bBoxName);
    bBoxDiv.innerHTML = ajaxObj.response;
  };

  ajaxObj.runAJAX();
}

function mainUpdateDateName ( dField ) {
  var dayStrObj  = document.getElementById(dField + "_DateName");
  var mainYear  = document.getElementById(dField + "_year");
  var mainMonth = document.getElementById(dField + "_month");
  var mainDay   = document.getElementById(dField + "_day");
  var pYear  = mainYear.options[mainYear.selectedIndex].value;
  var pMonth = mainMonth.options[mainMonth.selectedIndex].value - 1;
  var pDay   = mainDay.options[mainDay.selectedIndex].value;

  var weekday=new Array(7);
  weekday[0] = "Sunday";
  weekday[1] = "Monday";
  weekday[2] = "Tuesday";
  weekday[3] = "Wednesday";
  weekday[4] = "Thursday";
  weekday[5] = "Friday";
  weekday[6] = "Saturday";

  var dayStr = new Date (pYear, pMonth, pDay);
  var curDay = dayStr.getDay();
  var curDayStr = weekday[curDay];

  if ( pMonth != dayStr.getMonth() ) {
    mainMonth.selectedIndex = dayStr.getMonth();
    mainDay.selectedIndex   = dayStr.getDate() - 1;
  }

  dayStrObj.innerHTML = curDayStr;
}

/* Autocomplete */
function mainClearAutoComplete( sDivName ) {
  if ( sDivName ) { ClearDivList.unshift( sDivName ); }
}

function mainUpdateClearACList( sDivName ) {
  var sDiv;

  for( i=0; i < ClearDivList.length; i++ ) {
    if ( ClearDivList[i] != sDivName ) { 
      sDiv = document.getElementById( ClearDivList[i] );
      sDiv.innerHTML = "";
    } 
  } 
}

function mainAutoCompleteFormElements( sFormID ) {
  sForm = document.getElementById( sFormID );

  for(i=0; i< sForm.elements.length; i++) {
    sForm.elements[i].onfocus = function() { mainUpdateClearACList("tac_" + this.name); }
  }
}

function getCursorPosition( iField ) {
  var r;

  if ( iField.createTextRange ) {
     r = document.selection.createRange().duplicate();
     r.moveEnd('character', iField.value.length);
     if (r.text == '') { return iField.value.length; }
     else { return iField.value.lastIndexOf(r.text); }
  }
  else { return iField.selectionStart; }
}

function getStringArrayPosition( iStr, mStart ) {
  var c = 0;
  for( i=mStart; i > 0; i-- ) {
    if ( iStr.charAt(i) == "," || iStr.charAt(i) == ";" ) { c++; }
    
  }

  return c;
}

function mainAutoCompleteSelect( iFname, uFname, lIndex, iValue, oValue, sDivName, multiEntry ) {
  var iFel = document.getElementById( iFname );
  var uFel = document.getElementById( uFname );
  var sDiv = document.getElementById( sDivName );

  if ( multiEntry ) {
    mField = iFel.value.split(/[ \t]*[,;][ \t]*/);
    mField[lIndex] = oValue;
    iFel.value = mField.join(", ", mField) + ", ";
    iFel.focus();
  }
  else { iFel.value = oValue; }

  /* Update another field? */
  if ( uFel ) {
    /* Clear the list */
    for(i=uFel.options.length; i >= 0; --i ) { uFel.options[i] = null; }
    nIndex = uFel.options.length;
    uFel.options[nIndex] = new Option( oValue, iValue );
    if ( uFel.onchange ) { uFel.onchange(); }
  }

  sDiv.innerHTML = "";
}

function mainAutoCompleteLocal(iField, uFname, sArray, sDivName, pKey, tabCheck, multiEntry) {
  var fMatch = 0;
  var tabKeys ="9;";
  var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
  var i, j, j_next, mField, lField;
  var sDiv = document.getElementById( sDivName );

  // Tabcheck and no Tab pressed: do not proceed
  if ( tabCheck && tabKeys.indexOf(pKey+";") == -1 ) { return false; }

  // Multi-entry?
  lIndex = 0;
  if ( multiEntry ) { 
    mField = iField.value.split(/[ \t]*[,;][ \t]*/);
    mStart = getCursorPosition(iField);
    lIndex = getStringArrayPosition(iField.value, mStart);
    lField = mField[lIndex];
  }
  else { lField = iField.value; }

  // Now search the array
  fList = "";
  lElement = "";
  for (i in sArray) {
    if (sArray[i][1].toUpperCase().indexOf(lField.toUpperCase()) == 0) {
      nLoc = lField.length;
      fList += '<DIV onClick=\'mainAutoCompleteSelect("' + iField.name + '","' + uFname + '",'
		+ lIndex + ',"' + sArray[i][0] + '","' + sArray[i][1] + '","'
		+ sDivName + '",' + multiEntry + ')\'><B>' + sArray[i][1].substr(0,nLoc) + '</B>' + sArray[i][1].substr(nLoc) + "</DIV>\n";
      fMatch += 1;
      lElement = sArray[i];
    }
  }

  //  If found then let us show
  if ( fMatch ) {
    if ( fMatch > 2 ) { height = " STYLE='height: 64px;'"; } else { height = ""; }
    if ( lElement[1].length > 20 ) { height += " STYLE='width: 320px;'"; }
    sDiv.innerHTML = "<DIV CLASS=mainautocomplete" + height + ">" + fList + "</DIV>";
  }
  else { sDiv.innerHTML = ""; }

  //  If tab pressed make sure the single entry is auto selected
  if (tabKeys.indexOf(pKey+";") != -1) {
    if ( fMatch == 1 ) {
      mainAutoCompleteSelect( iField.name, uFname, lIndex, lElement[0], lElement[1], sDivName, multiEntry);
    }
    else { sDiv.innerHTML = ""; }
  }
}

function mainAutoCompleteAjax(iField, uFname, sURL, sDivName, pKey, tabCheck, multiEntry) {
  var ajaxObj = new sack();

  ajaxObj.URLString = "first_visit=no";
  ajaxObj.requestFile = sURL + "/" + encodeURI(iField.value);

  ajaxObj.onCompletion = function(){
    var sArray = new Array();
    var tArray = ajaxObj.response.split(";##;");
    for( i=0; i < tArray.length; i++ ) {
      sArray[i] = tArray[i].split(";#;");
    }
    mainAutoCompleteLocal(iField, uFname, sArray, sDivName, pKey, tabCheck, multiEntry);
  };

  ajaxObj.runAJAX();
}

function mainMakeFieldMandatory( aBox, sName, aValues ) {
  var sField = document.getElementById('span_' + sName);
  var aSelect = aBox[aBox.selectedIndex].value;

  fMatch = 0;
  if ( aSelect ) {
    t = aValues.split(",");
    for( i=0; i < t.length; i++ ) {
      if ( t[i] == aSelect ) { fMatch = 1; }
    }
  }

  if  ( fMatch ) {
    sField.style.fontWeight = 'bold';
  }
  else { 
    sField.style.fontWeight = 'normal';
  }
}

