// looks for the menu and hidden windows, even if this page was opened in a new window
var mparent=window.top;
if(mparent.DeskNowMain) {
	mparent=mparent.DeskNowMain;
}

var menuwindow=mparent.menu;


try {
while(typeof(menuwindow) == "undefined") {
	mparent=mparent.opener;
	if(mparent == null) {
		break;  // can't find the menu
	}
    if(mparent.mparent) {
        // take the mparent of my parent.
        mparent=mparent.mparent;
    }
    else {
        mparent=mparent.top;
	    if(mparent.DeskNowMain) {
		    mparent=mparent.DeskNowMain;
	    }
    }
    menuwindow=mparent.menu;
}
var menubottomwindow=mparent.menubottom;
while(typeof menubottomwindow == "undefined") {
	mparent=mparent.opener;
	if(mparent == null) {
		break;  // can't find the menu
	}
	mparent=mparent.top;
	menubottomwindow=mparent.menu;
}
}
catch(e){}


function dOnFocus() {
  mparent.clearAlertMark();
}
if(mparent && navigator.userAgent.toLowerCase().indexOf("gecko")!=-1) {
 window.onfocus=dOnFocus;
}

var getAllSelectBoxes_pre;
function getAllSelectBoxes_crit(ce) {
        if(ce.tagName.toLowerCase()=="input") {
            if(ce.name && startsWith(ce.name,getAllSelectBoxes_pre)) {
                return true;
            }
        }
        return false;
}
function getAllSelectBoxes(form,pre) {
    getAllSelectBoxes_pre=pre;
    var els=getChildElementsByCriterium(form,getAllSelectBoxes_crit);
    return els;
}
// invert the checked status of a group of check boxes
function toggleSelection2(form,prename) {
	var elements=getAllSelectBoxes(form,prename);
    for(var i=0;i<elements.length;i++) {
        var el=elements[i];
        el.checked=!el.checked;
	}
}

// invert the checked status of a group of check boxes
function toggleSelection(form) {
	toggleSelection2(form,"select_");
}

function isAnySelected(form) {
	var elements=getAllSelectBoxes(form,"select_");
	for(var i=0;i<elements.length;i++) {
		var el=elements[i];
        if(el.checked) return true;
	}
    return false;
}

function getAllSelected(form) {
    var s=new Array();
	var elements=getAllSelectBoxes(form,"select_");
    for(var i=0;i<elements.length;i++) {
		var el=elements[i];
        if(el.checked) {
            s[s.length]=el.name.substring(7);
        }
	}
    return s;
}

// cancels an event from bubbling up
function cancelIt(evt) {
  var e = (typeof evt != 'undefined') ? evt : event;
  e.cancelBubble = true;
}

function isSplit() {
if(window.parent) {
  if(window.parent.frames["list"]) return true;
}
return false;
}

// open a link in the parent (if this is a section of a splitframe, like a mailfolder), or in the current win if not split
function openInSplitParent(url) {
var w;
if(isSplit()) {
  w=window.parent;
}
else {
  w=window;
}
w.location.href=url;
}

/** open or download a file*/
function fileOD(urlopen,urldownload) {
// tries to open a file in the proper way.
// urlopen= download url for inline content disposition
// urldownload= download url for attachment content disposition
// if the extension is html, opens inline, in a new browser window
// note that the most strictly appropriate way would be to use also the request's "Accept" header (matching it with the mimetypes database in web.xml) to see other filetypes that the browser can open inline.
// however, most users do not like to edit an Excel spreadsheet in an IE window...
// finally, it is fairly easy to change this code so that other file extensions get opened 'inline'
if(endsWith(urlopen,"html")|| endsWith(urlopen,"htm")) {
  fileO(urlopen);
}
// otherwise shows download/open dialog
else {
  fileD(urldownload);
}
}

function lowercaseExtension(s) {
	var pos=s.lastIndexOf(".");
	if(pos!=-1) {
		s=s.substr(0,pos)+s.substr(pos).toLowerCase();
	}
	return s;
}
function fileO(urlopen) {
  urlopen=lowercaseExtension(urlopen);
  var w=window.open("about:blank","_blank");
  w.location.href=urlopen; // this will open inside the browser's window
}

function fileD(urldownload) {
	urldownload=lowercaseExtension(urldownload);
  // if you have IE on XP before XP ServicePack 2, and notice that the menu buttons don't work after downloading a file or attachment,
  // change this variable to true. Then right-click on the page and select 'Refresh' to reload the script.
  var safe_mode_for_ie_before_sp2=false;


  if(safe_mode_for_ie_before_sp2) {
    if(isIe()) {
      window.open(urldownload,"_blank");
    }
    else {
      window.location.href=urldownload;
    }
  }
  else {
    window.location.href=urldownload;
  }

}

function forceReload() {
  mparent.location="home.do?Action=Reload";
}



/**
       Handles internationalization on the JavaScript side.
       Relies on a I18nKeys map to translate into the current language. The map is typically created from a separate js file, created dynamically by the servlet-side.
*/
function I18NTranslate(key) {
    if(mparent && mparent.I18NMap) {
        var s=mparent.I18NMap[key];
        if(s) {
            return s;
        }
        // key not found
        return key;
    }
    else {
        return key;
    }
}

function I18NTranslate3(key,v1,v2,v3) {
    key=I18NTranslate(key);
    key=replace2(key,"{0}",v1,true);
    key=replace2(key,"{1}",v2,true);
    key=replace2(key,"{2}",v3,true);
    return key;
}

/** Get a user preference, or def if the preference is not set. */
function getUserPreference(name,def) {
    if(mparent && mparent.DNUP) {
        var s=mparent.DNUP[name];
        if(s) {
            return s;
        }
    }
    return def;
}

function isUserPreference(name,def) {
    var s=getUserPreference(name,def);
    return new String(s).toLowerCase()=="true";
}
/** create a link to open pages in DeskNow.
* servletName: "mail.do" , etc.
* params: {param1:value1, param2:value2 }
*/
function makeLink(servletName,params) {
    var s=servletName+"?";
    var first=true;
    for(var i in params) {
        if(!first) s=s+'&';
        var name=i;
        var value=params[i];
        s=s+name+'='+value;
        first=false;
    }
    if(mparent) {
        if(!first) s=s+'&';
        s=s+"Vs="+mparent.DNGlobalSettings.antiXssParam;
    }
    s=encodeURI(s);
    return s;
}

var updateTreeInfo;
function doUpdateTreeNodes() {
    var uns=updateTreeInfo.uinfo;
    debug2("doUpdateTreeNodes: "+uns.length);
    for(var i=0;i<uns.length;i++) {
        menuwindow.updateTreeNode(uns[i].nodeId,uns[i].text);
    }
}

function updateTreeNodes(treeInfo) {
    updateTreeInfo=treeInfo;
    doUpdateTreeNodes();
//    window.setTimeout('doUpdateTreeNodes()',300); //delay a bit to avoid slowing down page rendering
}

var pc_isPrevEnabled;
var pc_isNextEnabled;
var pc_curBlockSize=0;
var pc_firstNav=true;
var checkBlockSizes=true;
function updateNavigationInfo() {
    debug2("precontent","updatenav start");
    var st;
    if(curNav.total>0) {
        st=curNav.blockStart+1;
    }
    else {
        st=0;
    }

    var t=I18NTranslate3("{0} to {1} of {2}",st,curNav.blockStart+curNav.actualSize,curNav.total);
    debug2("precontent","updatenav 1");
    menu_changeItemProperty("blocknavmenu","blocksizeinfo",1,t,true); // set the '1 to 10 of 20' label
    debug2("precontent","updatenav 2");

    if(checkBlockSizes) {
	    // make sure that the correct block size is marked as selected in the dropdown menu
        var sizes=new Array(15,20,25,30,50,100);
        for(var i=0;i<sizes.length;i++) {
            var s=sizes[i];
            if(curNav.blockSize==s && s!=pc_curBlockSize) {
                menu_check("blocksizemenu","blockNavOption_"+s);
            }
            else if (curNav.blockSize!=s && s==pc_curBlockSize) {
                menu_uncheck("blocksizemenu","blockNavOption_"+s);
            }
        }
        pc_curBlockSize=curNav.blockSize;
        checkBlockSizes=false;
    }
    debug2("precontent","updatenav 3");

	// manages navigation links
    if(pc_firstNav) {
	    // at the first page load, clear the URLs (buttons are greyed)
        menu_changeItemProperty("blocknavmenu","blocknavprev",2,"",false); // url
        menu_changeItemProperty("blocknavmenu","blocknavnext",2,"",false); // url
    }
    if(curNav.blockStart>0) {
        if(pc_firstNav || !pc_isPrevEnabled) {
	        // enables the icon
            menu_changeItemProperty("blocknavmenu","blocknavprev",34,"",false); // type normal (opposite to disabled)
            var i=themeRes("icons/prev.gif");
            menu_changeItemProperty("blocknavmenu","blocknavprev",29,i,true); // image
        }
        var prevStart=curNav.blockStart-curNav.blockSize;
        if(prevStart<0) prevStart=0;

	    // set the link for prev
        menu_changeItemProperty("blocknavmenu","blocknavprev",62,"doAjaxNav("+prevStart+","+curNav.blockSize+")",false); // clickfunction
        pc_isPrevEnabled=true;
    }
    else {
        if(pc_firstNav || pc_isPrevEnabled) {
            menu_changeItemProperty("blocknavmenu","blocknavprev",34,"disabled",false); // type
            var i=themeRes("icons/prevdisabled.gif");
            menu_changeItemProperty("blocknavmenu","blocknavprev",29,i,false); // image
            menu_changeItemProperty("blocknavmenu","blocknavprev",62,"",true); // clickfunction
        }
        pc_isPrevEnabled=false;
    }
    debug2("precontent","updatenav 4");

    if((curNav.blockStart+curNav.actualSize)<curNav.total) {
        if(pc_firstNav || !pc_isNextEnabled) {
	        // enables the next icon
            menu_changeItemProperty("blocknavmenu","blocknavnext",34,"",false); // type
            var i=themeRes("icons/next.gif");
            menu_changeItemProperty("blocknavmenu","blocknavnext",29,i,true); // image
        }
	    // set the next link
        var nextStart=curNav.blockStart+curNav.blockSize;
        menu_changeItemProperty("blocknavmenu","blocknavnext",62,"doAjaxNav("+nextStart+","+curNav.blockSize+")",false); // clickfunction
        pc_isNextEnabled=true;
    }
    else {
        if(pc_firstNav || pc_isNextEnabled) {
	        // disables the next icon and link
            menu_changeItemProperty("blocknavmenu","blocknavnext",34,"disabled",false); // type
            var i=themeRes("icons/nextdisabled.gif");
            menu_changeItemProperty("blocknavmenu","blocknavnext",29,i,true); // image
            menu_changeItemProperty("blocknavmenu","blocknavnext",62,"",false); // clickfunction
        }
        pc_isNextEnabled=false;
    }

	if(pc_firstNav) {
		// set the 'First' item
		menu_changeItemProperty("blocksizemenu","blocknavfirst",2,"",false); // url
		menu_changeItemProperty("blocksizemenu","blocknavfirst",62,"doAjaxNav(0,"+curNav.blockSize+")",false); // clickfunction

		// set the 'Last' item
		menu_changeItemProperty("blocksizemenu","blocknavlast",2,"",false); // url
		var lastStart=curNav.total-curNav.blockSize;
		if(lastStart<0) {
			lastStart=0;
		}
		menu_changeItemProperty("blocksizemenu","blocknavlast",62,"doAjaxNav("+lastStart+","+curNav.blockSize+")",false); // clickfunction

		// set the 'Jump to' item
		menu_changeItemProperty("blocksizemenu","blocknavjump",2,"",false); // url
		menu_changeItemProperty("blocksizemenu","blocknavjump",62,"bnav_AjaxJump()",false); // clickfunction

	}
    debug2("precontent","updatenav end");
    pc_firstNav=false;

    debug2("precontent","scroll start");
    setInnerScrollNow('scrollgridbody',new Array("pagetop","gridheading_1","pagebottom"));
    debug2("precontent","scroll end");
    grid_recalc();
    debug2("precontent","grid end");
}

/** The 'Jumpt to' function in ajax navigation */
function bnav_AjaxJump() {
  var total=curNav.total;
  var s=window.prompt(I18NTranslate('Please input the item number that you want to jump to')+" (1-"+total+")","");
  if(s) {
    var ok=isValidInteger(s);
    if(ok) {
      ok=(s<=total);
    }
    if(!ok) {
      alert(I18NTranslate("Invalid number"));
      return;
    }
    s--; // internal numbering is from 0
	doAjaxNav(s,curNav.blockSize);
  }
}
/** called by BlockNavOption.jsp to change blocksize */
function blockNavOptionClicked(size) {
    doAjaxNav(curNav.blockStart,size);
    checkBlockSizes=true;
}



/** Equivalent to <dn:write html="true"> .*/
function toHtml(s) {
    debug("toHtml: "+mparent.htmlEntities);

    if(!isDefined(s)) {
        return "&nbsp;";
    }
    if(s.length==0) {
        return "&nbsp;";
    }
    var r="";
    for(var i=0;i<s.length;i++) {
        var c=s.charCodeAt(i);
        if(c==10) { // \n
            r=r+"<br />";
        }
        else if(c==13) { // \r
        }
        else if(c==9) { // \t
            r=r+"&nbsp;&nbsp;&nbsp;&nbsp;";
        }
        else {
            var entity = null;
            if(c < 256) {
                entity = mparent.htmlEntities[c];
            }
            if(!isDefined(entity)) {
                r=r+s.charAt(i);
            } else {
                r=r+"&" + entity + ";";
            }
        }
    }
    debug("toHtml result: "+r);
    return r;
}

/*
window.setTimeout('dotest()',300); //delay a bit to avoid slowing down page rendering
function dotest() {
var c="<";
c=toHtml(c);
alert(c);
}
*/
