/**
 * Copyright CloverWorxs Inc.
 */
var cwGlobalObject=new Object();
var cwNumberAllowedKeyCodes = new Array(8,37,38,39,40,46,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,229);

function cwIsContainedInArray(arrays,value){
    if("undefined"==typeof(arrays))return false;
    if("undefined"==typeof(arrays.length)){
        if(arrays==value)return true;
    }
    else{
        for(var i = 0; i < arrays.length; i++) {
            if(arrays[i]==value)return true;
        }
    }
    return false;
}

function cwOnlyKeyNumber(){
    var key = window.event.keyCode;
    if(event.ctrlKey || event.altKey || event.shiftKey || !cwIsContainedInArray(cwNumberAllowedKeyCodes,key)){
        //event.keyCode=0;
        event.returnValue=false;
        return false;
    }
    return true;
}

function cwIsNatureNumber(value){
    if(isNaN(value)){
        return false;
    }
    if(value<=0){
        return false;
    }
    var invalid = new Array(".","x");
    for(var i=0;i<invalid.length;i++){
        if(value.indexOf(invalid[i])>=0){
            return false;
        }
    }
    for(var i=0;i<value.length;i++){
        var c = value.charAt(i);
        var isNumber = false;
        for(var j=0;j<10;j++){
            if(c == j){
                isNumber = true;
                break;
            }
        }
        if(!isNumber) return false;
    }
    return true;
}

function cwTrimWhiteSpace(inputString){
    var retValue = inputString;
    var whiteSpace = new Array(' ','\t','\n','\r');
    var ch = retValue.charAt(0);
    while (cwIsContainedInArray(whiteSpace,ch)) {
        retValue = retValue.substr(1, retValue.length-1);
        ch = retValue.charAt(0);
    }
    ch = retValue.charAt(retValue.length-1);
    while (cwIsContainedInArray(whiteSpace,ch)) {
        retValue = retValue.substr(0, retValue.length-1);
        ch = retValue.charAt(retValue.length-1);
    }
    return retValue;
}

function cwNotEmpty(o){
  if(typeof(o)!="undefined" && o!=null && o!="") return true;
  return false;
}

function cwIsSelectedForCheckBox(checkbox){
  if("undefined"==typeof(checkbox)) {
    return false;
  }
  if("undefined"==typeof(checkbox.length)){
    if(checkbox.disabled==false && checkbox.checked){
      return true;
    }
  }else{
    for (var i=0; i<checkbox.length; i++) {
      if(checkbox[i].disabled==false && checkbox[i].checked){
        return true;
      }
    }
  }
  return false;
}

function cwSelectCheckBox(checkbox,bSelect){
  if("undefined"==typeof(checkbox)) {
    return;
  }
  if("undefined"==typeof(checkbox.length)){
    if(checkbox.disabled==false){
      checkbox.checked = typeof(bSelect)=="undefined"?!checkbox.checked:bSelect;
    }
  }else{
    for (var i=0; i<checkbox.length; i++) {
      if(checkbox[i].disabled==false){
        checkbox[i].checked=typeof(bSelect)=="undefined"?!checkbox[i].checked:bSelect;
      }
    }
  }
}

/**
 * for portal.jsp and for all block open/close
 */
function cwDisplayMenu(oBlock,owner,picture,contextPath){
    if(oBlock.style.display==""){
        oBlock.style.display="none";
        cwClosedStatus(owner,picture,contextPath);
    }else{
        oBlock.style.display="";
        cwOpenedStatus(owner,picture,contextPath);
    }
}
function cwSwitchTitleBarIcon(oBlock,owner,picture,isOver,contextPath){
    if(oBlock.style.display==""){
        if(isOver)cwClosedStatus(owner,picture,contextPath);
        else cwOpenedStatus(owner,picture,contextPath);
    }else{
        if(isOver)cwOpenedStatus(owner,picture,contextPath);
        else cwClosedStatus(owner,picture,contextPath);
    }
}
function cwOpenedStatus(owner,picture,contextPath){
    owner.className="boxtitle_icon";
    if(picture!=""){
        owner.style.backgroundImage="url("+contextPath+picture+")";
    }
}
function cwClosedStatus(owner,picture,contextPath){
    owner.className="boxtitle_icon2";
    if(picture!=""){
        var re = new RegExp("/replaceable/icon/", "gi");
        var picture = picture.replace(re,"/replaceable/icon/mirror/");
        owner.style.backgroundImage="url("+contextPath+picture+")";
    }
}

function cwAdjustImageSize(theImg,defWidth,defHeight){
    if(theImg.width>defWidth)theImg.style.width=defWidth;
    if(theImg.height>defHeight)theImg.style.width=(theImg.width*defHeight)/theImg.height;
}

/**
 * for portal.jsp and for all block popup menu
 */
var curentBlockPopupMenu;
var hiddingSelectBoxArrays = new Array("selectPortalStyle1","answersSelectBox1","selRenderBlock");
function cwLMPopUp(parentObj,menuID) {
    var leftX,topY;
    var selfObj = document.getElementById(menuID);
    if(selfObj.offsetWidth<(document.body.clientWidth-window.event.clientX)){
        leftX = document.body.scrollLeft+window.event.clientX-10;
    }else{
        leftX = document.body.scrollLeft+window.event.clientX-selfObj.offsetWidth+10;
    }
    if(selfObj.offsetHeight<(document.body.clientHeight-window.event.clientY)){
        topY = document.body.scrollTop+window.event.clientY-10;
    }else{
        topY = document.body.scrollTop+window.event.clientY-selfObj.offsetHeight+10;
    }
    document.getElementById(menuID).style.left=leftX;
    document.getElementById(menuID).style.top=topY;
    curentBlockPopupMenu=menuID;
    cwShowMenu(selfObj.offsetLeft,selfObj.offsetTop,selfObj.offsetWidth,selfObj.offsetHeight);
    document.body.attachEvent ("onmouseup",cwHideMenu);
}
function cwShowMenu(ml,mt,mw,mh){
  document.getElementById(curentBlockPopupMenu).style.visibility = "visible";
  for(var i = 0; i < hiddingSelectBoxArrays.length; i++) {
    var oSelStyle = document.getElementById(hiddingSelectBoxArrays[i]);
    if(oSelStyle!=null && "undefined"!=typeof(oSelStyle)){
      var ox = cwGetOffsetLeft(oSelStyle); oy = cwGetOffsetTop(oSelStyle);
      if(ml+mw>ox && mt<oy) document.getElementById(hiddingSelectBoxArrays[i]).style.visibility = "hidden";
    }
  }
}
function cwHideMenu(){
  document.body.detachEvent("onmouseup",cwHideMenu);
  document.getElementById(curentBlockPopupMenu).style.visibility = "hidden";
  for(var i = 0; i < hiddingSelectBoxArrays.length; i++) {
    var oSelStyle = document.getElementById(hiddingSelectBoxArrays[i]);
    if(oSelStyle!=null && "undefined"!=typeof(oSelStyle)){
      document.getElementById(hiddingSelectBoxArrays[i]).style.visibility = "visible";
    }
  }
}
/*
function cwHideMenuOnOuterRange(oElement){
  var oSource = event.srcElement;
  var oTarget = event.toElement;
  if(oSource.tagName.toUpperCase()=="DIV" && oSource.id==oElement.id){
		if(!oSource.contains(oTarget)){
			cwHideMenu();
		}
	}
  if(event.clientX<=oElement.offsetLeft  || event.clientX>=oElement.offsetLeft+oElement.clientWidth
    || event.clientY<=oElement.offsetTop || event.clientY>=oElement.offsetTop+oElement.clientHeight){
    cwHideMenu();
  }
}
*/
var cwHideMenuTimer=null;
function cwShowMenuTimeout(parentObj,menuID) {
  cwLMPopUp(parentObj,menuID);
  cwHideMenuClearTimeout(parentObj);
}
function cwHideMenuStartTimeout(oElement) {
		cwHideMenuTimer = setTimeout("cwHideMenu()", 1);
}
function cwHideMenuClearTimeout(oElement) {
	if (cwHideMenuTimer){
	  clearTimeout(cwHideMenuTimer);
	}
	cwHideMenuTimer = null;
}
function cwGetOffsetLeft(layer) {
    var value = 0;
    object = layer;
    value = object.offsetLeft;
    while (object.tagName != "BODY" && object.offsetParent) {
        object = object.offsetParent;
        value += object.offsetLeft;
    }
    return (value);
}
function cwGetOffsetTop(layer) {
    var value = 0;
    object = layer;
    value = object.offsetTop;
    while (object.tagName != "BODY" && object.offsetParent) {
        object = object.offsetParent;
        value += object.offsetTop;
    }
    return (value);
}
function cwDisplayBlockItemTR(key){
    var oPlusImg = document.getElementById("BlockItemPlusIMG_"+key);
    var oMinusImg = document.getElementById("BlockItemMinusIMG_"+key);
    var oTr = document.getElementsByName("BlockItemTR_"+key);
    if(oTr.length>0){
        if(oTr[0].style.display==""){
            oPlusImg.style.display="";
            oMinusImg.style.display="none";
            for(var i=0;i<oTr.length;i++){
                cwCloseDescendantsTR(oTr[i].lontoo);
                oTr[i].style.display="none";
            }
        }else{
            oPlusImg.style.display="none";
            oMinusImg.style.display="";
            for(var i=0;i<oTr.length;i++){
                oTr[i].style.display="";
            }
        }
    }
}
function cwCloseDescendantsTR(key){
    var oPlusImg = document.getElementById("BlockItemPlusIMG_"+key);
    var oMinusImg = document.getElementById("BlockItemMinusIMG_"+key);
    var oTr = document.getElementsByName("BlockItemTR_"+key);
    for(var i=0;i<oTr.length;i++){
        oPlusImg.style.display="";
        oMinusImg.style.display="none";
        if(oTr[i].style.display==""){
            cwCloseDescendantsTR(oTr[i].lontoo);
            oTr[i].style.display="none";
        }
    }
}

/**
 * for change page panel width
 */
var startXPosition=0;
var startLeftWidth=0;
var startMiddleWidth=0;
var startRightWidth=0;
function getSpacifyObjectWidth(o){
  if("undefined"!=typeof(o)){
    if("undefined"==typeof(o.length))return(o.clientWidth);
    else return(o[0].clientWidth);
  }
  return(0);
}
function setSpacifyObjectWidth(o,value){
  if(value<=0)return;
  if("undefined"!=typeof(o)){
    if("undefined"==typeof(o.length)){
      o.style.width=value;
    }else{
      for(var i=0;i<o.length;i++){o[i].style.width=value;}
    }
  }
}
function startDragAndDrop(){
    startXPosition = window.event.clientX;
    startLeftWidth = getSpacifyObjectWidth(document.all.leftPortalPanelID);
    startMiddleWidth = getSpacifyObjectWidth(document.all.middlePortalPanelID);
    startRightWidth = getSpacifyObjectWidth(document.all.rightPortalPanelID);
}
function inprocessDragAndDrop(index){//1=first from left;2=second from left;...
    var offsetWidth = window.event.clientX-startXPosition;
    if(index==1 && startMiddleWidth>offsetWidth){
        setSpacifyObjectWidth(document.all.leftPortalPanelID,startLeftWidth+offsetWidth);
        setSpacifyObjectWidth(document.all.middlePortalPanelID,startMiddleWidth-offsetWidth);
    }else if(index==2 && startRightWidth>offsetWidth){
        setSpacifyObjectWidth(document.all.middlePortalPanelID,startMiddleWidth+offsetWidth);
        setSpacifyObjectWidth(document.all.rightPortalPanelID,startRightWidth-offsetWidth);
    }
    if(typeof(document.all.portalPanelWidthDisplay)!="undefined"){
        var lWidth = getSpacifyObjectWidth(document.all.leftPortalPanelID);
        var mWidth = getSpacifyObjectWidth(document.all.middlePortalPanelID);
        var rWidth = getSpacifyObjectWidth(document.all.rightPortalPanelID);
        document.all.portalPanelWidthDisplay.innerHTML=""+lWidth+", "+mWidth+", "+rWidth+"&nbsp;";
        window.status=""+lWidth+", "+mWidth+", "+rWidth+"";
    }
}
function endDragAndDrop(url,percent){
    // url is a whole contextpath and servlet path with its all querystring; for example:
    // "/skills/portal/portalView.do?fwcid=&layoutLWidth=%LEFTWIDTH%&layoutMWidth=%MIDDLEWIDTH%&layoutRWidth=%RIGHTWIDTH%";
    // or relative url, for example: "?fwcid=&layoutLWidth=%LEFTWIDTH%&layoutMWidth=%MIDDLEWIDTH%&layoutRWidth=%RIGHTWIDTH%";
    // replace %LEFTWIDTH% %MIDDLEWIDTH% %RIGHTWIDTH% with end value(s).
    // if percent is true, return percent value; or return absolute value.
    var leftWidth = getSpacifyObjectWidth(document.all.leftPortalPanelID);
    var middleWidth = getSpacifyObjectWidth(document.all.middlePortalPanelID);
    var rightWidth = getSpacifyObjectWidth(document.all.rightPortalPanelID);
    if(percent=="true"){
        var endTotalWidth = leftWidth+middleWidth+rightWidth;
        leftWidth = Math.round(100*leftWidth/endTotalWidth);
        middleWidth = Math.round(100*middleWidth/endTotalWidth);
        rightWidth = Math.round(100*rightWidth/endTotalWidth);
        setSpacifyObjectWidth(document.all.leftPortalPanelID,leftWidth+"%");
        setSpacifyObjectWidth(document.all.middlePortalPanelID,middleWidth+"%");
        setSpacifyObjectWidth(document.all.rightPortalPanelID,rightWidth+"%");
    }
    var re = new RegExp("%LEFTWIDTH%", "gi");
    url = url.replace(re,leftWidth);
    var re = new RegExp("%MIDDLEWIDTH%", "gi");
    url = url.replace(re,middleWidth);
    var re = new RegExp("%RIGHTWIDTH%", "gi");
    url = url.replace(re,rightWidth);
    XMLHttpObj.sendAsyncRequest("GET",url);
}

/**
 * for image outline
 */
function cwMakePictureAsOutline(o){
    var refValue=50;orgWidth=o.width;
    if(o.width>refValue){
        while(o.width!=refValue){o.style.width=refValue;}
        o.style.width=Math.min(orgWidth,o.parentElement.clientWidth);
    }
}
function cwFlexPictureByMouseWheel(o){
    var zoom=parseInt(o.style.zoom, 10)||100;zoom+=event.wheelDelta/12;if (zoom>0) o.style.zoom=zoom+'%';
    return false;
}

/**
 * for ajax
 */
function cwCreateXMLHTTPRequest(){
    return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}

var XMLHttpObj = {
    _objPool: [],
    _getInstance: function (){
        //for (var i = 0; i < this._objPool.length; i ++){
        //    if (this._objPool[i].readyState == 0 || this._objPool[i].readyState == 4){
        //        return this._objPool[i];
        //    }
        //}
        //this._objPool[this._objPool.length] = this._createObj();
        //return this._objPool[this._objPool.length - 1];
        return this._createObj();
    },

    _createObj: function (){
        if (window.XMLHttpRequest){ //Mozilla
            var objXMLHttp = new XMLHttpRequest();
        }else{                      //IE
            var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
            for(var n = 0; n < MSXML.length; n ++){
                try{
                    var objXMLHttp = new ActiveXObject(MSXML[n]);
                    break;
                }
                catch(e){
                }
            }
         }

        if (objXMLHttp.readyState == null){
            objXMLHttp.readyState = 0;

            objXMLHttp.addEventListener("load", function (){
                    objXMLHttp.readyState = 4;
                    if (typeof objXMLHttp.onreadystatechange == "function"){
                        objXMLHttp.onreadystatechange();
                    }
                },  false);
        }
        return objXMLHttp;
    },

    sendAsyncRequest: function (method, url, callback ,parameter, data){
       this._sendRequest(method, url, true,callback ,parameter, data);
    },

    sendSyncRequest: function (method, url, data){
       return this._sendRequest(method, url, false, "", "", data);
    },

    _sendRequest: function (method, url, async, callback, parameter, data){
        var objXMLHttp = this._getInstance();
        with(objXMLHttp){
            try{//no cache
                if (url.indexOf("?") > -1){
                    url += "&randnum=" + Math.random();
                }else{
                    url += "?randnum=" + Math.random();
                }

                open(method, url, async);

                //set charset
                setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

                if (typeof(data)!="undefined" && data!=""){
                  send(data);
                }else{
                  send();
                }

                if (typeof(callback)!="undefined" && callback!=""){
                  onreadystatechange = function (){
                      if (objXMLHttp.readyState == 4 && (objXMLHttp.status == 200 || objXMLHttp.status == 304)){
                          callback(objXMLHttp,parameter);
                      }
                  }
                }else{
                 return objXMLHttp;
                }
            }
            catch(e){
            }
        }
    }
};


/**
 * tree.js
 */

function createXMLDOM(){
  var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
  xmlDoc.async = false;
  return xmlDoc;
}
function loadXMLText(xmlText){
  var xmlDoc = createXMLDOM();
  xmlDoc.loadXML(xmlText);
  return xmlDoc;
}
function loadXMLFile(xmlFile){
  var xmlDoc = createXMLDOM();
  xmlDoc.load(xmlFile);
  return xmlDoc;
}
function transformXML(xmlText,xslFile){
  var xmlDoc = loadXMLText(xmlText);
  var xslDoc = loadXMLFile(xslFile);
  return xmlDoc.documentElement.transformNode(xslDoc);
}

function clickOnEntity(entity){
  var fontx = document.getElementsByName('fontx');
  for(i=0; i < fontx.length; i++){
    fontx(i).style.color="black";
    fontx(i).style.background="white";
  }
  oFont = entity.childNodes(0).all["fontx"];
  if("undefined"!=typeof(oFont) && oFont!=null){
    oFont.style.color="white";
    oFont.style.background="navy";
  }

  if(entity.opened=="false")expand(entity);
  else collapse(entity);
}

function expand(entity){
  var oImage = entity.childNodes(0).all["opcol"];
  if("undefined"!=typeof(oImage)) oImage.src = entity.openedPict;
  oImage = entity.childNodes(0).all["image"];
  if("undefined"!=typeof(oImage)) oImage.src = entity.openedIcon;

  for(i=0; i < entity.childNodes.length; i++){
    if(entity.childNodes(i).tagName.toUpperCase() == "DIV"){
      entity.childNodes(i).style.display = "block";
    }
  }
  entity.opened = "true";
}

function collapse(entity){
  var oImage = entity.childNodes(0).all["opcol"];
  if("undefined"!=typeof(oImage)) oImage.src = entity.closedPict;
  oImage = entity.childNodes(0).all["image"];
  if("undefined"!=typeof(oImage)) oImage.src = entity.closedIcon;

  for(var i=0; i < entity.childNodes.length; i++){
    if(entity.childNodes(i).tagName.toUpperCase() == "DIV"){
      entity.childNodes(i).style.display = "none";
      collapse(entity.childNodes(i));
    }
  }
  entity.opened = "false";
}

function expandAll(entity){
  expand(entity);
  for(var i=0; i < entity.childNodes.length; i++){
    if(entity.childNodes(i).tagName.toUpperCase() == "DIV"){
      expandAll(entity.childNodes(i));
    }
  }
}

function cwAttachStringToTable(htmltext,oTable,index){
  /**
  ** @param htmltext is tr/td, like <tr><td>text</td></tr>;
  ** @oTable which will be attached with tr string
  ** @index insert position
  **/
  var oDiv = document.createElement("DIV");
  htmltext = htmltext.replace(/(^\s*)|(\s*$)/g, "");
  if(htmltext.indexOf("<table")!=0 && htmltext.indexOf("<TABLE")!=0) {
    oDiv.innerHTML="<TABLE>"+htmltext+"</TABLE>";
  } else {
    oDiv.innerHTML=htmltext;
  }

  //var oTRs = oDiv.getElementsByTagName("tr");
  var oTRs = oDiv.childNodes[0].childNodes[0].childNodes;
  for(var i=0; i<oTRs.length; i++){
    myNewRow = oTable.insertRow(index+i);
    myNewRow.mergeAttributes(oTRs[i]);
    for(var j=0;j<oTRs[i].childNodes.length;j++){
      oTD = oTRs[i].childNodes[j];
      myNewCell = myNewRow.insertCell();
      myNewCell.mergeAttributes(oTD);
      myNewCell.innerHTML=oTD.innerHTML;
    }
  }
}

function cwGetAncestorByTagName(o,tagName){
  var found=false;
  var parent = o.parentElement;
  while(parent!=null && !found){
    if(parent.tagName.toLowerCase()==tagName.toLowerCase()){
      found=true;
      return parent;
    }
    parent = parent.parentElement;
  }
  return null;
}

function cwContainsOnSpecifiedArray(oArray, oElement){
  for(var i=0; i<oArray.length; i++){if(oArray[i]==oElement)return i;}
  return -1;
}

function cwOpenOrCloseChildNode(oTable,oTr,display){
  if(typeof(oTr.name)=="undefined" || typeof(oTr.opened)=="undefined"){
    return;
  }
  var trArray = new Array(oTr);
  var idArray = new Array(oTr.name);
  var openedArray = new Array(oTr.opened);
  var render = (display==true?"":"none");
  for(var i=oTr.rowIndex+1; i<oTable.rows.length; i++){
    var rowTr = oTable.rows(i);
    if(typeof(rowTr.parent)!="undefined"){
      var number=cwContainsOnSpecifiedArray(idArray,rowTr.parent);
      if(number != -1){
        if(typeof(rowTr.name)!="undefined" && typeof(rowTr.opened)!="undefined"){
          trArray.push(rowTr);
          idArray.push(rowTr.name);
          openedArray.push(rowTr.opened);
        }
        if(display==true){render=(openedArray[number]=="true" && trArray[number].style.display==""?"":"none");}
        rowTr.style.display=render;
      }else{
        break;
      }
    }else{
      break;
    }
  }
}

function getTreeTagPlusParameter(oTable){
  var oDivArray = oTable.parentElement.getElementsByTagName("DIV");
  for(var i=0;i<oDivArray.length;i++){
    if(oDivArray[i].id.toLowerCase()=="value"){
      return oDivArray[i].innerText;
    }
  }
  return "";
}

function cwAddDeferForScriptElement(html){
  var re = new RegExp("<script[ ]*","gi") ;
  return html.replace(re, "<script DEFER=\"true\" ");
}

function cwClickThisTreeNode(oImg,key,fwcid,feature,pid){
  beginProgress("",false,false);
  var oTable = cwGetAncestorByTagName(oImg,"TABLE");
  var curTr = cwGetAncestorByTagName(oImg,"TR");
    var url = "?fwcid="+fwcid+"&feature="+feature+"&key="+key+"&action=";
  if(curTr.opened=="true"){
    curTr.opened="false";
    if(typeof(oImg.closeIcon)!="undefined" && oImg.src!=oImg.closeIcon){oImg.src=oImg.closeIcon;}
    cwOpenOrCloseChildNode(oTable,curTr,false);//alert(url+"close");
    XMLHttpObj.sendAsyncRequest("GET",url+"close");
    endProgress();
  }else{
    curTr.opened="true";
    if(typeof(oImg.openIcon)!="undefined" && oImg.src!=oImg.openIcon){oImg.src=oImg.openIcon;}
    if(curTr.loaded=="true"){
      cwOpenOrCloseChildNode(oTable,curTr,true);//alert(url+"open");
      XMLHttpObj.sendAsyncRequest("GET",url+"open");
      endProgress();
    }else{
      url+="fetchSubtree&value="+getTreeTagPlusParameter(oTable);//alert(url);
      XMLHttpObj.sendAsyncRequest("GET",url,cwOpenCurrentTreeNodeCallback,new Array(oTable,curTr.rowIndex));
    }
  }
}

function cwOpenCurrentTreeNodeCallback(xmlHTTP,params){
  //alert(xmlHTTP.responseText);
  //document.write(xmlHTTP.responseText);
  params[0].deleteRow(params[1]);
  cwAttachStringToTable(xmlHTTP.responseText,params[0],params[1]);
  endProgress();
}

function cwSelectPopupMenu(o, key, url, pid) {
  beginProgress("",false,false);
  var oDiv = cwGetAncestorByTagName(o, "DIV");
  var oTable = cwGetAncestorByTagName(oDiv,"TABLE");
  url+="&key=" + key;
  url+="&value="+getTreeTagPlusParameter(oTable);
  XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshWholeTreeNodeCallback,new Array(oTable));
}

function cwSelectPopupMenu2(o, key, url, pid) {
  var randomParam = "&dddatetttime="+new Date().getTime();
  document.location.href=url+"&key="+key+randomParam;
}

function cwChangeQuestionOrder(oldIndex, newIndex) {
  beginProgress("",false,false);
  var baseURL = "?fwcid=testContents&feature=test&action=insert";
  baseURL += "&value=testContent&nodeIndex=" + oldIndex + "&nodeNewIndex=" + newIndex;
  var oTable = document.all.RecorderTestTreeTag;
  XMLHttpObj.sendAsyncRequest("GET",baseURL,cwRefreshWholeTreeNodeCallback,new Array(oTable));
}

function cwEditTreeNodeTitle(oInputBox,oElement, params) {
  if (oInputBox.value==''){
    return false;
  }
  beginProgress("",false,false);
  var newTitle = oInputBox.value;
  var url = params[0];
  var treeName = params[1];
  var oTable = document.getElementById(treeName);
  url+="&title="+encodeURIComponent(newTitle);
  url+="&value="+getTreeTagPlusParameter(oTable);
  XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshWholeTreeNodeCallback,new Array(oTable));

  var titleBar = document.all.treeNodeTitleInBar;
  if(titleBar!=null) {
	  titleBar.innerText = newTitle;
  }
}

function cwSelectThisTreeNode(o,key,fwcid,feature,action,pid,msg){
  beginProgress("",false,false);
  var oTable = cwGetAncestorByTagName(o,"TABLE");
  var curTr = cwGetAncestorByTagName(o,"TR");
  var randomParam = "&dddatetttime="+new Date().getTime();
  var baseURL = "?fwcid="+fwcid+"&feature="+feature+"&action="+action+"&key="+key;
  var url = baseURL+"&target=part";
  if(action.toUpperCase()=='OPENALL'){
    url+="&value="+getTreeTagPlusParameter(oTable);//alert(url);
    XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshWholeTreeNodeCallback,new Array(oTable));
  }else if(action.toUpperCase()=='SELECT'){
    if(cwNeedToRefreshSpecifiedFrameUI(feature)){
      document.location.href=baseURL+randomParam;
    }else{
      cwSaveBookmarkURLOnAJAXSelect(baseURL);
      url = url + "&parentReferer="+encodeURIComponent(location);
      XMLHttpObj.sendAsyncRequest("GET",url,cwSelectThisTreeNodeCallback,new Array(oTable,curTr,key,fwcid,feature,pid));
    }
  }else if(action.toUpperCase()=='DEL'){
    if(confirm(msg)){
      XMLHttpObj.sendAsyncRequest("GET",url,cwDelCurrentTreeNodeCallback,new Array(oTable,fwcid,feature,action));
    }else{
      endProgress();
    }
  }else if((fwcid.toUpperCase()=='TESTCONTENTS' && (feature.toUpperCase()=='TESTPAGE' || feature.toUpperCase()=='TESTFOLDER') && action.toUpperCase()=='BEGINMOVE')
         ||(fwcid.toUpperCase()=='TEST' && feature.toUpperCase()=='TEST' && action.toUpperCase()=='MOVE')
	     ||(fwcid.toUpperCase()=='COURSE' && feature.toUpperCase()=='COURSE' && action.toUpperCase()=='MOVE')
	     ||(fwcid.toUpperCase()=='MODULEEDIT' && feature.toUpperCase()=='MODULE' && action.toUpperCase()=='MOVE')){	
    document.location.href="?fwcid="+fwcid+"&feature="+feature+"&action="+action+"&key="+key+randomParam;
  }else if(action.toUpperCase()=='ADD'){
    document.location.href="?fwcid=test&feature=question&action=createQuestion&key="+key+randomParam;
  }else{
    XMLHttpObj.sendAsyncRequest("GET",url,cwEditCurrentTreeNodeCallback,new Array(oTable,fwcid,feature,action,key));
  }
}

function cwNeedToRefreshSpecifiedFrameUI(feature){
  if(location.pathname.lastIndexOf("/recorder/courseView.do")>-1){
    var rightBar = document.all.rightPortaldisplayBarID;
    if((typeof(rightBar)=="undefined" && (feature=="folder" || feature=="page"))
       ||(typeof(rightBar)!="undefined" && feature!="folder" && feature!="page")){
      return true;
    }
  }
  return false;
}

function cwRefreshRecordContextTreeUI(feature){
  if(location.pathname.lastIndexOf("/recorder/courseView.do")>-1){
    if(feature=="folder" || feature=="page"){
      var url = "?fwcid=contextContent&feature=contextNode&action=refresh";
      XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshRecordContextTreeUICallback,new Array());
    }
  }
}

function cwRefreshRecordContextTreeUICallback(xmlHTTP,params){
  cwFillinTheTDinnerHTML(xmlHTTP.responseText,document.all.rightPortalPanelID);
}

function cwSaveBookmarkURLOnAJAXSelect(suffix){
  if(typeof(document.all.bookmarkURLInputHiddenID)!="undefined"){
    var url = location.protocol+"//"+location.host+location.pathname;
    document.all.bookmarkURLInputHiddenID.value=url+suffix;
    //alert(document.all.bookmarkURLInputHiddenID.value);
  }
}
function cwRefreshWholeTreeNode(params){
  var rootName = params[0].rows(0).name;
  if(rootName!=null && rootName!="" && typeof(rootName)!="undefined" && rootName.indexOf("treeFolderTr_")==0){
    var rootKey = rootName.substr("treeFolderTr_".length, rootName.length-1);
    var url = "?fwcid="+params[1]+"&feature="+params[2]+"&action=fetchSubtree";
    url+="&value="+getTreeTagPlusParameter(params[0])+"&key="+rootKey;
    XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshWholeTreeNodeCallback,new Array(params[0]));
  }
}

function cwRefreshWholeTreeNodeCallback(xmlHTTP,params){
  while(params[0].rows.length>1)params[0].deleteRow(params[0].rows.length-2);
  cwAttachStringToTable(xmlHTTP.responseText,params[0],0);
  endProgress();
}

function cwSelectThisTreeNodeCallback(xmlHTTP,params){
  //var rootName = params[0].rows(0).name;
  //if(rootName!=null && rootName!="" && typeof(rootName)!="undefined" && rootName.indexOf("treeFolderTr_")==0){
  //  var rootKey = rootName.substr("treeFolderTr_".length, rootName.length-1);
  //  var url = "?fwcid="+params[3]+"&feature="+params[4]+"&action=fetchSubtree";
  //  url+="&value="+getTreeTagPlusParameter(params[0])+"&key="+rootKey;//alert("url="+url);
  //  XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshWholeTreeNodeCallback,new Array(params[0]));
  //}
  cwRefreshWholeTreeNode(new Array(params[0],params[3],params[4]));
  if(typeof(document.all.fetchHotResourceTD)!="undefined" && params[3]=="resource"){
    var url = "?fwcid=resource&feature=resourceBank&action=fetchHotResource";
    XMLHttpObj.sendAsyncRequest("GET",url,cwFillinFetchHotResourceTD,new Array());
  }
  params[0].selected=params[2];
  cwRefreshRecordContextTreeUI(params[4]);
  cwFillinTheTDinnerHTML(xmlHTTP.responseText);
  endProgress();
}
function cwFillinFetchHotResourceTD(xmlHTTP,params){
  cwFillinTheTDinnerHTML(xmlHTTP.responseText,document.all.fetchHotResourceTD);
}

function cwSelectCurrentTreeNodeCallback(xmlHTTP,params){//disable on 2008-8-22 by dony, replace with cwSelectThisTreeNodeCallback
  var fetchURL = "?fwcid="+params[3]+"&feature="+params[4]+"&action=fetchSubtree";
  fetchURL+="&range=self&value="+getTreeTagPlusParameter(params[0])+"&key=";
  if(typeof(params[0].selected)!="undefined" && params[0].selected!="" && params[0].selected!="null"){
    var oImage = document.getElementById("treeFolderImg_"+params[0].selected);
    var oldSelectedTr = cwGetAncestorByTagName(oImage,"TR");
    var url = fetchURL+params[0].selected; //alert(url);
    XMLHttpObj.sendAsyncRequest("GET",url,cwOpenCurrentTreeNodeCallback,new Array(params[0],oldSelectedTr.rowIndex));
  }
  if(params[1].opened=="false"){//2. if the tr is not been opened, open it and select it.
    var oImage = document.getElementById("treeFolderImg_"+params[2]);
    cwClickThisTreeNode(oImage,params[2],params[3],params[4],params[5]);
  }else{//3. if the tr is opened, then selected it.
    var url = fetchURL+params[2];//alert(url);
    XMLHttpObj.sendAsyncRequest("GET",url,cwOpenCurrentTreeNodeCallback,new Array(params[0],params[1].rowIndex));
  }
  params[0].selected=params[2];
  cwRefreshRecordContextTreeUI(params[4]);
  cwFillinTheTDinnerHTML(xmlHTTP.responseText);
  endProgress();
}

function cwFillinTheTDinnerHTML(html,oTarget){
  if(oTarget==null || oTarget=="" || typeof(oTarget)=="undefined"){
    oTarget=document.all.middlePortalPanelBodyID;
  }
  if(oTarget!=null && oTarget!="" && typeof(oTarget)!="undefined"){
    oTarget.innerHTML="";
    oTarget.innerHTML=cwAddDeferForScriptElement(html);
  }else{
    document.write(html);
  }
}

function cwEditCurrentTreeNodeCallback(xmlHTTP,params){//oTable,fwcid,feature
  cwFillinTheTDinnerHTML(xmlHTTP.responseText);
  if(params[3]=="move"){
    cwEditCurrentTreeNodeApply();
  }else{
    cwGlobalObject.table=params[0];
    cwGlobalObject.fwcid=params[1];
    cwGlobalObject.feature=params[2];
  }
  endProgress();
}
function cwEditCurrentTreeNodeApply(){
  //var rootName = cwGlobalObject.table.rows(0).name;
  //if(rootName!=null && rootName!="" && typeof(rootName)!="undefined" && rootName.indexOf("treeFolderTr_")==0){
  //  var rootKey = rootName.substr("treeFolderTr_".length, rootName.length-1);
  //  var url = "?fwcid="+cwGlobalObject.fwcid+"&feature="+cwGlobalObject.feature+"&action=fetchSubtree";
  //  url+="&value="+getTreeTagPlusParameter(cwGlobalObject.table)+"&key="+rootKey;//alert("url="+url);
  //  XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshWholeTreeNodeCallback,new Array(cwGlobalObject.table));
  //}
  cwRefreshWholeTreeNode(new Array(cwGlobalObject.table,cwGlobalObject.fwcid,cwGlobalObject.feature));
}
function cwDelCurrentTreeNodeCallback(xmlHTTP,params){//oTable,fwcid,feature,action
  cwFillinTheTDinnerHTML(xmlHTTP.responseText);
  if(params[3]=="del"){
    cwDelCurrentTreeNodeApply(params);
  }
  endProgress();
}
function cwDelCurrentTreeNodeApply(params){//oTable,fwcid,feature,action
  var table=params[0];
  var fwcid=params[1];
  var feature=params[2];
  var rootName = table.rows(0).name;
  if(rootName!=null && rootName!="" && typeof(rootName)!="undefined" && rootName.indexOf("treeFolderTr_")==0){
    var rootKey = rootName.substr("treeFolderTr_".length, rootName.length-1);
    var url = "?fwcid="+fwcid+"&feature="+feature+"&action=fetchSubtree";
    url+="&value="+getTreeTagPlusParameter(table)+"&key="+rootKey;//alert("url="+url);
    XMLHttpObj.sendAsyncRequest("GET",url,cwRefreshWholeTreeNodeCallback,new Array(table));
    cwSelectThisTreeNode(table.rows(0),rootKey,"testContents","test","select",0);
  }
}
function cwBackgroundSubmitWithIframe(theForm,refreshTree){
  var oIFrame = document.getElementById("backgroundSubmittedIFrameID");
  if(oIFrame==null || oIFrame=="" || typeof(oIFrame)=="undefined"){
    theForm.target="_self";
  }else{
    oIFrame.loaded="true";
    if(typeof(refreshTree)!="undefined" && refreshTree){oIFrame.apply="true";}
    theForm.target=oIFrame.name;
  }
  theForm.submit();
}
function cwLoadContentByIframe(theIFrame){
  if(theIFrame.loaded=='true'){
    theIFrame.loaded='false';
    if("undefined"!=typeof(theIFrame.contentWindow.document.all.middlePortalPanelBodyID)){
      window.location=theIFrame.contentWindow.location;
    }else{
     cwFillinTheTDinnerHTML(theIFrame.contentWindow.document.body.innerHTML);
     if(typeof(theIFrame.apply)!="undefined" && theIFrame.apply=="true"){cwEditCurrentTreeNodeApply();}
    }
    endProgress();
  }
}

function cwMeasureLength(string){
	var length=0;
	for(var i=0;i<string.length;i++){
		var code = string.charCodeAt(i);
		length += (code*1<256?1:2);
	}
	return length;
}
function cwGetFunctionName(func){
	var string = func.toString();
	//var start = string.indexOf("function")+"function".length;alert(start);
	var end = string.indexOf("(");
	string = string.substring(8,end);
	string = string.replace(new RegExp(" ", "gi"), "");
	string = string.replace(new RegExp("\\r", "gi"), "");
	string = string.replace(new RegExp("\\n", "gi"), "");
	return string;
}

/****
@param oElement is a xhtml object, it contains the text string;
@param size is a integer number, it is the input box's size, if (-1) unlimited;
@param maxlength is a integer number, it is the input box's maxlength, if (-1) unlimited;
@param callback is a function object, it is callback function;
@param args is a array object, it can contains string data only;
****/
function cwText2InputBox(oElement,size,maxlength,callback,args){
	if(oElement.hasChildNodes()
	  && oElement.childNodes.length>0
		&& typeof(oElement.childNodes[0].tagName)!="undefined"
		&& oElement.childNodes[0].tagName.toUpperCase()=="INPUT"){
		return;
	}
	var oldText = oElement.innerHTML;
	oElement.original = oldText;
  var randomx=(Math.round(Math.random()*9999999999));
	if(oElement.id=="")oElement.id="CloverWorxs"+randomx;
  var inputBox = '<input type="text"';
	inputBox += ' id="DascomApp'+randomx+'"';
	inputBox += ' class="border" style="cursor:text;"';
	if(size<=0){
		inputBox += ' size="'+(cwMeasureLength(oldText)*1+1)+'"';
		inputBox += ' onkeydown="this.size=cwMeasureLength(this.value)+1;';
  	inputBox += ' if(event.keyCode==13){this.blur();}"';
	}else{
		inputBox += ' size="'+((cwMeasureLength(oldText)*1+1)>size?size:cwMeasureLength(oldText)*1+1)+'"';
		inputBox += ' onkeydown="if(this.size<'+size+')this.size=cwMeasureLength(this.value)+1;';
  	inputBox += ' if(event.keyCode==13){this.blur();}"';
	}
	inputBox += ' onblur="javascript:cwSaveThisInputDataIfFinish(this,\''+oElement.id+'\',\''+cwGetFunctionName(callback)+'\'';
  if(typeof(args)!="undefined"){
    var values = "";
    for(var k=0;k<args.length;k++){
      var value = args[k];
      value = value.replace(new RegExp("%", "gi"), "25%");
      value = value.replace(new RegExp("'", "gi"), "39%");
      value = value.replace(new RegExp('"', "gi"), "34%");
      value = value.replace(new RegExp("#", "gi"), "23%");
      values += value+"#";
    }
    inputBox += ',\''+(values.length>0?values.substr(0,values.length-1):values)+'\'';
  }
  inputBox += ' );"';
	inputBox += ' value="'+oldText+'"';
  if(maxlength>0)inputBox += ' maxlength="'+maxlength+'"';
	inputBox += '>';
	oElement.innerHTML="";
	oElement.innerHTML=inputBox;
	var oInputBox = document.getElementById("DascomApp"+randomx);
	if(oInputBox!=null){
    oInputBox.attachEvent ("onclick",cwCancelBubble);
		oInputBox.select();oInputBox.focus();
	}
}
function cwCancelBubble(){
  window.event.cancelBubble = true;
}
function cwSaveThisInputDataIfFinish(oInputBox,oElementID,callbackFunc,arrayString){
  var oElement = document.getElementById(oElementID);
	if(oElement==null)return;
	if(oElement.original!=oInputBox.value){
		var callback = eval(callbackFunc);
		if(typeof(callback)=="function"){
			var result = false;
			if(typeof(arrayString)=="undefined"){
				result = callback(oInputBox,oElement);
			}else{
				var args = new Array();
				if(arrayString.length>0){
					args = arrayString.split("#");
					for(var k=0;k<args.length;k++){
						var value = args[k];
						value = value.replace(new RegExp("23%", "gi"), "#");
						value = value.replace(new RegExp("34%", "gi"), '"');
						value = value.replace(new RegExp("39%", "gi"), "'");
						value = value.replace(new RegExp("25%", "gi"), "%");
						args[k] = value;
					}
				}
				result = callback(oInputBox,oElement,args);
			}
			if(result==false){
				oInputBox.select();oInputBox.focus();
				return;
			}
		}
	}
  oElement.innerHTML = "";
  oElement.innerHTML = oInputBox.value;
}

/****
replace link for some specified situation.
@function perviewPortalWithoutLinks(vStyleFile) for iframe disable link;
@function tempAddDatetimeParameterForLinks() for ajax link add random number;
****/
function perviewPortalWithoutLinks(vStyleFile){
  var vStyleText = vStyleFile.substr(0, vStyleFile.length-4);
  var re = new RegExp("/skin[0-9]*/", "g");
  var tagArray = new Array("IMG","A");
  for(var n=0;n<tagArray.length;n++){
    var tags = document.body.getElementsByTagName(tagArray[n].toUpperCase());
    for(var i=0;i<tags.length;i++){
      if(tags[i].tagName.toUpperCase()=='A'){
        tags[i].href="?cssFile="+vStyleFile;
      }
      else if(tags[i].tagName.toUpperCase()=='IMG'){
        tags[i].src=tags[i].src.replace(re,"/"+vStyleText+"/");
      }
      else{//TODO
      }
    }
  }
}
function tempAddDatetimeParameterForLinks(){
  var tagArray = new Array("A");
  for(var n=0;n<tagArray.length;n++){
    var tags = document.body.getElementsByTagName(tagArray[n].toUpperCase());
    for(var i=0;i<tags.length;i++){
      if(tags[i].tagName.toUpperCase()=='A'){
        var excess="dddatetttime="+new Date().getTime();
        var href=tags[i].href;
        if(href.toLowerCase().indexOf("#?")==-1
          && href.toLowerCase().indexOf("javascript")==-1
          && href.toLowerCase().indexOf("dddatetttime=")==-1
          && href.toLowerCase().indexOf("?")!=-1){
          tags[i].href=href+(href.indexOf("?")==-1?"?":"&")+excess;
        }
      }
      else{//TODO
      }
    }
  }
}

//============================================
//======          add js code           ======
//======      pagation page method      ======
//======  added by crystal on 2006-8-9  ======
//============================================
function onFirst(id){
    var otable = document.getElementById(id);
    if(otable.isfirst=="true"){
        alert(otable.msg1);
    }
    service(id,3);
    otable.isfirst="true";
    otable.islast="false";
}

function onPrev(id){
    var otable = document.getElementById(id);
    service(id,1);
    otable.isfirst="false";
    otable.islast="false";
}

function onNext(id){
    var otable = document.getElementById(id);
    service(id,2);
    otable.isfirst="false";
    otable.islast="false";
}

function onLast(id){
    var otable = document.getElementById(id);
    if(otable.islast=="true"){
        alert(otable.msg2);
    }
    service(id,4);
    otable.isfirst="false";
    otable.islast="true";
}

function service(id,flag){
    var otable = document.getElementById(id);
    //alert("otable1 curpage == " + otable.curpage);
    var pageRows = otable.pageRows;
    //alert("otable2 pageRows == " + pageRows);
    var len = otable.rows.length;
    var pageCount = Math.ceil(len / pageRows);

    if(flag == 1) otable.curpage -= 1;
    if(flag == 2) otable.curpage += 1;

    if(flag==2){
        if(otable.curpage<=0){
            otable.curpage=1;
        }
        if(otable.curpage>pageCount-1){
            otable.curpage=0;
        }
    }
    if(flag==1){
        if(otable.curpage<0){
            otable.curpage=pageCount-1;
        }
        if(otable.curpage==pageCount){
            otable.curpage=0;
        }
    }
    //alert("otable3 curpage == " + otable.curpage);
    if(otable.curpage == '01'){
        otable.curpage=1;
    }

    if(flag==3){
        otable.curpage=0;
    }

    //alert("pageCount == " + pageCount);
    if(flag==4){
        if(pageCount>0){
            otable.curpage=pageCount-1;
        }else{
            otable.curpage=0;
        }
    }

    for(var i=0; i<len; i++){
        var curTr = otable.rows(i);
        if(i<pageRows*otable.curpage || i>(pageRows*(otable.curpage+1)-1)){
            curTr.style.display="none";
        }else{
            curTr.style.display="";
        }
    }
}