/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2008                                    */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/*********************************************************************/

//-------------------------------------------------------------
//  Quickplace Ajax library
//-------------------------------------------------------------

// Quickplace "AJAX" Object
function QPAjax()
{
	this.Request = QPAjax_Request;
	this.RequestJS = QPAjax_RequestJS;
	this.RequestXML = QPAjax_RequestXML;
	this.SubmitForm = QPAjax_SubmitForm;
	this.Error = QPAjax_Error;	  // Default error handler if none specified
}


// Make an XMLHTTP request;
//
// Required args:
//  url: the request URL
//  sFunc: "success" callback function with returned data as argument.
//
// Optional args:
//  meth: "get" or "post" ("get" is dojo.io.bind's default).
//  eFunc: "error" callback function with error code as argument.
//  type: The MIME type determining format of returned data.
//        Default is "text/plain" (response passed back "as is", as raw text).
//
// For info on dojo.io.bind, see http://dojo.jot.com/Tutorials/HelloWorld
//
function QPAjax_Request(url, sFunc, meth, eFunc, type)
{
	var theMethod = meth || "get";
	var theErrFunc = eFunc || this.Error;
	var theType = type || "text/plain";

	try {
		dojo.io.bind({
			url: url,
			method: theMethod,
			load: function(type, data, evt){sFunc(data)},
			error: function(type, error){theErrFunc(error)},
			mimetype: theType,
			transport: "XMLHTTPTransport"
		});
	}
	catch(e) {
		this.Error(e);
	}
}


// Request data assumed to be javascript code,
// try to evaluate and run the returned javascript.
//
// Example:
// --------
// demo.js on the server contains:
//
// function helloWorld() {
//     alert( "Hello world!\n" +
//         "I'm some javascript." );
//     return "I have returned";
// }
// helloWorld();
//
// Your client-side code:
//
// function showReturnValue( type, evaldObj ) {
//     alert('The script returned ' + evaldObj );
// }
//
// ajax = new QPAjax();
// ajax.RequestJS((demoLocation + 'demo.js'), showReturnValue);
//
function QPAjax_RequestJS(url, sFunc, meth, eFunc)
{
	QPAjax_Request(url, sFunc, meth, eFunc, "text/javascript");
}


// Request XML data,
// try to create an XML document from the returned XML.
// (This data can then be parsed using the JS DOM APIs).
function QPAjax_RequestXML(url, sFunc, meth, eFunc)
{
	QPAjax_Request(url, sFunc, meth, eFunc, "text/xml");
}


// Submit a Form asynchronously
//
// No URL required, because the form's action property is used.
//
// Required args:
//  formId: the id of the <form> tag
//  sFunc: "success" callback function with returned data as argument.
//
// Optional args:
//  eFunc: "error" callback function with error code as argument.
//
function QPAjax_SubmitForm(formId, sFunc, eFunc)
{
	var theErrFunc = eFunc || this.Error;

	try {
		dojo.io.bind({
			load: function(type, data, evt){sFunc(data)},
			error: function(type, error){theErrFunc(error)},
			formNode: document.getElementById(formId),
			mimetype: "text/plain",
			encoding: "utf-8"
		});
	}
	catch(e) {
		this.Error(e);
	}
}

// FIX ME: report error
function QPAjax_Error(error)
{
	alert(QuickrLocaleUtil.getStringResource("AJAX.ERROR") + error.message);
}
/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2008                                    */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/*********************************************************************/

//-------------------------------------------------------------
//  Quickplace Context Menu library
//-------------------------------------------------------------

var g_pageX = 0;
var g_pageY = 0;

//---------------------------------------------------------------------

function QP_ContextMenu_Item(type, label, action, target, title, title_disabled, icon, submenu)
{
	this.type = type; 
	this.label = label || "";
	this.action = action || "";
	this.target = target || "_self";
	this.title = title || this.label;
	this.title_disabled = title_disabled || this.title;
	this.icon = icon;
	this.submenu = submenu;

}

function QP_ContextMenu(name, extraClass, bIcons)
{
	this.name				= name;
	this.extraClass		= extraClass;
	this.items				= new Array();
	this.bShowIcons		= (bIcons===undefined ? true : bIcons);
	
	this.write				= QP_ContextMenu_write;
	this.show				= QP_ContextMenu_show;
	this.addItem			= QP_ContextMenu_addItem;
	this.addSubmenu		= QP_ContextMenu_addSubmenu;
	this.addHTML			= QP_ContextMenu_addHTML;
	this.addSeparator		= QP_ContextMenu_addSeparator;
	this.addImage			= QP_ContextMenu_addImage;
	this.fixName			= QP_ContextMenu_fixName;
	this.makeItem			= QP_ContextMenu_makeItem;
	this.makeSeparator	= QP_ContextMenu_makeSeparator;
	this.addBizCard		= QP_ContextMenu_void;

	this.HTML				= 0;
	this.LINK				= 1;
	this.LINK_SUBMENU		= 2;
	this.IMAGE				= 3;
	this.SEPARATOR			= 4;
}

function QP_PersonMenu(szDN, szCN, szDisplayName, szEmail, szPhone, szPhoto, szDescription, szProfileUnid)
{ 
	var fixedName = QP_ContextMenu_fixName(szDN);

	// Inherit from QP_ContextMenu
	this.base				= QP_ContextMenu;
	this.base(fixedName);

	this.CN					= szCN;
	this.DN					= szDN;
	this.displayName		= szDisplayName || szCN;
	this.email				= szEmail || "";
	this.phone				= szPhone || "";
	this.photo				= szPhoto || "";
	this.description		= szDescription || "";
	this.profileUnid		= szProfileUnid || "";
	
	this.addBizCard		= QP_PersonMenu_addBizCard;
	this.makeBizCard		= QP_PersonMenu_makeBizCard;
	this.write				= QP_PersonMenu_write;
}
QP_PersonMenu.prototype = new QP_ContextMenu;

// ---------------------------------------------------------

function QP_ContextMenu_void()
{ 
	return false;
}

function QP_ContextMenu_get(name)
{ 
	return document.getElementById(name + "_Menu");
}

function QP_ContextMenu_exists(name)
{ 
	return (document.getElementById(name + "_Menu") != null);
}

// Convert menu name (which may be a Notes canonical name) to a valid HTML Id that we can use
// as a basis for menu-related HTML elements.
// Must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]),
// hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
function QP_ContextMenu_fixName(name) {
	if (typeof(name) == "undefined")
		return "";
	else
		return name.replace(/[.=\/ ]/g, "-");
//	return encodeForUrl(encodeURIComponent(name));
}

// Set coordinates to mouse click position
function QP_ContextMenu_mouseTracker(e)
{
    e = e || window.Event || window.event;
    g_pageX = e.pageX || e.clientX;
    g_pageY = e.pageY || e.clientY;
}


// ---------------------------------------------------------

function QP_ContextMenu_addItem(label, action, target, title, icon, title_disabled)
{ 
	this.items[this.items.length] = new QP_ContextMenu_Item(this.LINK, label, action, target, title, title_disabled, icon);
}

function QP_ContextMenu_addSubmenu(label, action, target, title, icon, title_disabled, submenu)
{ 
	this.items[this.items.length] = new QP_ContextMenu_Item(this.LINK_SUBMENU, label, action, target, title, title_disabled, icon, submenu);
}

function QP_ContextMenu_addImage(label, action, target)
{ 
	this.items[this.items.length] = new QP_ContextMenu_Item(this.IMAGE, label, action, target);
}

function QP_ContextMenu_addHTML(label, action, target)
{ 
	this.items[this.items.length] = new QP_ContextMenu_Item(this.HTML, label, action, target);
}

function QP_ContextMenu_addSeparator(label, action, target)
{ 
	this.items[this.items.length] = new QP_ContextMenu_Item(this.SEPARATOR, "", "", "");
}

// ----------------------------------------------------------
// Generate HTML for one menu item
//
function QP_ContextMenu_makeItem(szLabel, szAction, szTitle)
{
	var title = szTitle || szLabel;
	var action = szAction || "#";
	var html = "";

	html += '<li><a id="' + this.name + '_' + QP_ContextMenu_fixName(szLabel) + '"';
	if (szAction == "") {
		 // Item is inactive - show as greyed out
		 html += ' href="javascript:void(0);" class="h-contextMenu-disabled"';
	}
	else {
		 if (title != "")
			  html += ' title="' + title + '"';
		 html += ' href="' + action + '"';
	}
	html += '>' + szLabel + '</a></li>';
	return html;
}

// ----------------------------------------------------------
// Generate HTML separator for context menu items
//
function QP_ContextMenu_makeSeparator()
{
	return '<li class="h-context-separator"><hr/></li>';
}


// ----------------------------------------------------------

function QP_PersonMenu_addBizCard(szDisplayName, szEmail, szPhone, szPhoto, szDescription, szUNID)
{ 
	this.displayName		= szDisplayName || this.szCN;
	this.email				= szEmail || "";
	this.phone				= szPhone || "";
	this.photo				= szPhoto || "";
	this.description		= szDescription || "";
	this.profileUnid		= szUNID || "";
}

// ----------------------------------------------------------
// Generate HTML separator for context menu items
//
function QP_PersonMenu_makeBizCard()
{
	var html = "";
	html += '<div class="photoCard">';
	html += '<img id="' + this.name + '_photo" src="' 
		+ getMemberPhotoLink(this.CN, this.DN, this.DisplayName, this.email, this.photo, this.profileUnid)
		+ '" alt="">';
	html += '</div>';

	html += '<div class="businessCard">';
	html += '<ul>';
	html += '<li id="' + this.name + '_name" class="cardName">' + this.displayName +'</li>';
	html += '<li id="' + this.name + '_email">' + this.email + '</li>';
	html += '<li id="' + this.name + '_desc">' + this.description + '</li>';
	html += '<li id="' + this.name + '_phone">' + this.phone + '</li>';
	html += '</ul>';
	html += '</div>';
	return html;
}

// ----------------------------------------------------------

function QP_PersonMenu_write()
{ 
	var html = "";

	// Create the span that surrounds the entire menu
	var menu = document.createElement("span");
	menu.id = (this.name + "_Menu");
	if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ())){menu.style.display="none";}
	else menu.style.left="-9999px";
	menu.style.position="absolute";

	// Create unordered list
	html += '<div class="personMenu">';

	html += this.makeBizCard();

	html += '<div class="personMenuActions">';

	html += '<ul id="' + this.name + '_Top"';
	for (var i = 0; i < this.items.length; i++)
	{
		if (this.items[i].type == this.LINK) {
			html += this.makeItem(this.items[i].label, this.items[i].action);
		}
		else if (this.items[i].type == this.SEPARATOR) {
			 html += this.makeSeparator();
		}
	}
	html += '</ul>';
	html += '</div>';
	html += '</div>';

	menu.innerHTML = html;
	document.body.appendChild(menu);
}



// ----------------------------------------------------------

function QP_ContextMenu_write()
{ 
	var ul = document.createElement("ul");
	ul.className="lotusActionMenu";
 	if (this.extraClass)
 		ul.className += (" " + this.extraClass);
	ul.style.opacity="0.999999";
	if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ())){ul.style.display="none";}
	else ul.style.left="-9999px";
	
	var bAddSep=false;
	for (var i = 0; i < this.items.length; i++)
	{
		switch (this.items[i].type) {
		case this.LINK:
			var li=document.createElement("li");
			var a=document.createElement("a");

			a.id=this.name+"_"+QP_ContextMenu_fixName(this.items[i].label);
			a.innerHTML=this.items[i].label;

			var liClass="";
			var action=this.items[i].action;
			if (action == "") {
				// Item is inactive
				liClass="disabled"; // FIX ME: temporary until One UI style exists
				a.href="#";
				a.onclick=function(){return false;}
			}
			else {
				a.href=action;
				a.target=(this.items[i].target=="_blank" ? "_blank" : "_self");
				a.onmouseover=function(){QP_ContextMenu_hideSubmenus(this.parentNode.parentNode.id);};
			}

			if (bAddSep) {
				if (liClass.length > 0)
					liClass += " ";
				liClass += "lotusMenuSeparator";
				bAddSep=false;
			}

			if (liClass.length > 0)
				li.className=liClass;

			li.appendChild(a);
			ul.appendChild(li);
			break;

		case this.LINK_SUBMENU:
			var li=document.createElement("li");

			var a=document.createElement("a");
			a.href="#";
			a.onclick=function(){return false;}
			a.innerHTML=this.items[i].label;

			var liClass="submenu";
			if (this.items[i].submenu == "") {
				// Item is inactive
				liClass += " disabled"; // FIX ME: temporary until One UI style exists
			}
			else {
				a.id=this.name+"__SUB__"+this.items[i].submenu;
				a.onmouseover=function(){
					var smName=this.id.substring(this.id.lastIndexOf("__SUB__")+7);
					QP_ContextMenu_hideSubmenus(this.parentNode.parentNode.id);
					QP_ContextMenu_showSubmenu(this, smName);
				};
			}

			if (bAddSep) {
				liClass += " lotusMenuSeparator";
				bAddSep=false;
			}

			li.className=liClass;
			li.appendChild(a);
			ul.appendChild(li);
			break;

		case this.SEPARATOR:
			bAddSep=true;
			break;

		default:
			break;
		}
	}

	var id=this.name+"_Menu";
	var m1=dojo.byId(id);
	if (m1) {
		// menu already exists - replace it
		var pa=m1.parentNode;
		pa.replaceChild(ul,m1);
		ul.id=id;
	}
	else {
		// create new
		var div = document.createElement("div");
		div.style.position="absolute";
		if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ())){div.style.right="0px";}
		else 
		div.style.left="0px";
		div.style.top="0px";
		div.style.zIndex="900";
		div.appendChild(ul);
		ul.id=id;
		document.body.appendChild(div);
	}	
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// DISPLAY FUNCTIONS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Active menu and item w/in menu
var g_activeMenu = null;
var g_activeItem = null;

// Active menu "stack"
var g_activeIdx = -1;
var g_visibleMenu = new Array();

// Offsets for precise positioning of submenus.
// May need adjusting if changes made in CSS
var hOffsetAdjust = 4;
var vOffsetAdjust = 6;

// Return absolute position of an elem as [x,y]
function findPos(elem)
{
	var x = y = 0;
	if (elem.offsetParent) {
		x = elem.offsetLeft
		if(document.body.dir=='rtl'){x+=elem.offsetWidth;}
		y = elem.offsetTop
		while (elem = elem.offsetParent) {
			x += elem.offsetLeft
			y += elem.offsetTop
		}
	}
	return [x,y];
}

// Show a submenu beside the current active menu item
function QP_ContextMenu_showSubmenu(item, menu)
{
	var pos = findPos(item);
	g_activeItem = item;
	var RTLV = 0;
	if(document.body.dir=='rtl'){RTLV=2*item.offsetWidth;}
	QP_ContextMenu_show(menu,false,(pos[0]+item.offsetWidth-hOffsetAdjust)+5-RTLV, (pos[1]-vOffsetAdjust)+6);
}

// Show a menu (any type)
function QP_ContextMenu_show(menu, bHidePrev, x, y)
{
	if (x && y) {
		// coordinates specified
		g_pageX = x;
		g_pageY = y;
	}
	var bHide = (bHidePrev===undefined ? true : bHidePrev);
	if (bHide)
		 QP_ContextMenu_hide();

	g_activeMenu = document.getElementById(menu + "_Menu");
	if (g_activeMenu) {
		// Store the menu id on the "stack"
		g_visibleMenu[++g_activeIdx] = g_activeMenu;

		// adjust the X/Y position so that the entire Menu will show
		var mWidth = g_activeMenu.offsetWidth;
		var mHeight = g_activeMenu.offsetHeight;

		if (typeof(window.innerWidth)=='number') {
			//Non-IE
			if (window.innerHeight < (g_pageY + document.body.scrollTop + mHeight))
				g_activeMenu.style.top = (window.innerHeight - mHeight - 2) + "px";
			else
				g_activeMenu.style.top =  (g_pageY + document.body.scrollTop) + "px";
		}
		else if(document.documentElement && document.documentElement.clientHeight) {
			//IE 6+ in standards compliant mode
			if (document.documentElement.clientHeight < (g_pageY + document.body.scrollTop + mHeight))
				 g_activeMenu.style.pixelTop = (document.documentElement.clientHeight - mHeight - 2);
			else
				 g_activeMenu.style.pixelTop =  (g_pageY + document.body.scrollTop);
		}
		else if (document.all) {
			// IE
			if (document.body.clientHeight < (g_pageY + document.body.scrollTop + mHeight))
				 g_activeMenu.style.pixelTop = (document.body.clientHeight - mHeight - 2);
			else
				 g_activeMenu.style.pixelTop =  (g_pageY + document.body.scrollTop);
		}


		if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ()))
		{
		if (document.body.clientWidth < (mWidth+document.body.scrollWidth -g_pageX - mWidth)){
			g_activeMenu.style.right = (document.body.clientWidth - g_pageX - 2) + "px";

			}
		else
			g_activeMenu.style.right = (document.body.scrollWidth - g_pageX ) + "px";	
			
	
		}
		else
		{
			var RTLV = 0;
			if(document.body.dir=='rtl') {RTLV = mWidth;}
		if (document.body.clientWidth < (g_pageX + document.body.scrollLeft + mWidth))
			g_activeMenu.style.left = (document.body.clientWidth - mWidth - 2 - RTLV) + "px";
		else
			g_activeMenu.style.left = (g_pageX + document.body.scrollLeft-RTLV) + "px";
			}

		g_activeMenu.parentNode.style.zIndex = 1000 + g_activeIdx;
		g_activeMenu.style.display="block";
	}

	// Hide menu when click outside or timer elapses
	dojo.event.connect(document, "onmouseup", "onBodyClick");
//	dojo.event.connect(g_activeMenu, "onmouseout", "onMenuMouseout");
}

function onMenuMouseout(e)
{
	setTimeout("QP_ContextMenu_hide();",3000);
}

function onBodyClick(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	if (elem.className.indexOf("-context") < 0)
		 QP_ContextMenu_hide();
}

// Hide the active menu
function QP_ContextMenu_hide()
{
	while (g_activeIdx >= 0) {
		if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ())){g_visibleMenu[g_activeIdx--].style.display="none";}
		else g_visibleMenu[g_activeIdx--].style.left="-9999px";
	}
}

// Hide all submenus below the active menu
function QP_ContextMenu_hideSubmenus(menuId)
{
	thisMenu = document.getElementById(menuId);
	while (g_activeIdx >= 0 && g_visibleMenu[g_activeIdx] != thisMenu) {
		if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ())){g_visibleMenu[g_activeIdx--].style.display="none";}
		else g_visibleMenu[g_activeIdx--].style.left="-9999px";
	}
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// MAIN "ONLOAD" FUNCTION TO ATTACH EVENT HANDLERS TO ELEMENTS ON PAGE THAT CAN HAVE A CONTEXT MENU.
// CALL THIS ONLY AFTER PAGE IS LOADED.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function QP_ContextMenu_attachMenus(elem)
{
	var menuContainer=elem||document;

	if (UIContextMenusAreEnabled())
	{
		var bDocuments = UIContextMenuIsEnabled("documents");
		var bFolders = UIContextMenuIsEnabled("folders");
		var bMyPlaces = UIContextMenuIsEnabled("my_places");
		var bUserNames = UIContextMenuIsEnabled("user_names");

		try {
			// Attach handlers to all elements on page that require one
			var sl = menuContainer.getElementsByTagName("span");

			for (var i=0; i < sl.length; i++)
			{
				var span = sl[i];
				if ((bDocuments && span.className=="h-doc-anchor")
					|| (bFolders && span.className=="h-folder-anchor"))
				{
					var aTags = span.getElementsByTagName("a");
					if (aTags[0]) {
						dojo.event.connect(span, "onmouseover", "onDocMouseOver");
						dojo.event.connect(span, "onmouseout", "onDocMouseOut");
					}
				}
				else if (bUserNames && (span.className=="h-user-anchor" || span.className=="vcard"))
				{
					var aTags = span.getElementsByTagName("a");
					if (aTags[0]) {
 						dojo.event.connect(span, "onmouseover", "onPersonMouseOver");
 						dojo.event.connect(span, "onmouseout", "onPersonMouseOut");
					}
				}
				else if (bMyPlaces && span.className=="h-my-places-anchor") 
				{
					var aTags = span.getElementsByTagName("a");
					if (aTags[0]) {
						makeMyPlacesContextMenu(aTags[0].innerHTML, aTags[0].href, span);
						dojo.event.connect(span, "onmouseover", "onMyPlacesMouseOver");
						dojo.event.connect(span, "onmouseout", "onMyPlacesMouseOut");
					}
				}
				else if (bDocuments && span.className=="h-attachments-anchor") 
				{
					makeAttachmentsMenu(span.id, span.getAttribute("attachments"));
					dojo.event.connect(span, "onmouseover", "onAttMouseOver");
					dojo.event.connect(span, "onmouseout", "onAttMouseOut");
				}
			}
		}
		catch(e) {
			// Dojo not installed? Degrade to no menus
		}
	}
} // QP_ContextMenu_attachMenus()


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// EVENT HANDLERS FOR ATTACHMENT MENUS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function onAttMouseOver(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	var img = (elem.className=="h-contextMenu-icon") ? elem : elem.nextSibling;

	if (img) {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/menu_s.gif");
		dojo.event.connect(img, "onmouseup", "onAttContextMenu");
	}
	e.preventDefault();
}

function onAttMouseOut(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	var img = (elem.className=="h-contextMenu-icon") ? elem : elem.nextSibling;

	if (img) {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/menu_u.gif");
	}
	e.preventDefault();
}

function onAttContextMenu(e)
{
	var img = (e.target) ? e.target : e.srcElement;
	var pos = findPos(img);
	QP_ContextMenu_show(img.parentNode.id,true,pos[0],(pos[1]+img.offsetHeight));
	e.preventDefault();
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// EVENT HANDLER FOR "CREATE" MENU
//
// NOTE: Not supported in 8.1!
// These are here for 8.0 themes.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

var newQPObjMenu;

function onNewQPObjMouseOver(e)
{
	return false;
}

function onNewQPObjMouseOut(e)
{
	return false;
}

function createQPObjMenuItem(formUnid, title, description, docType, importField, publishedFormId)
{
	return false;
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// EVENT HANDLERS FOR DOCUMENT & FOLDER CONTEXT MENUS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function onDocMouseOver(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	var img = (elem.nodeName.toUpperCase()=="A") ? elem.nextSibling : elem;

	if (img) {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/menu_s.gif");
		img.onclick=function(){onDocContextMenu(this);return false;}
	}
	e.preventDefault();
}

function onDocMouseOut(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	var img = (elem.nodeName.toUpperCase()=="A") ? elem.nextSibling : elem;

	if (img) {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/menu_u.gif");
	}
	e.preventDefault();
}

function onDocContextMenu(btn)
{
	var a = btn.previousSibling;
	if (a) {
		// this is the doc name anchor
		try {
			var pos = findPos(btn);
			var imgSrc = btn.src;
			var url = (typeof(h_FolderStorage)=="undefined" ? a.href : "../../"+h_FolderStorage+"/"+a.id+"/?OpenDocument");

			dojo.io.bind ({
				url: url + "&Form=h_DocXml&nowebcaching",
				method: "get",
				mimetype: "text/xml",
				load: function (type, data, evt) {showDocContextMenu(a.id,a.href,data,btn,imgSrc,pos[0],(pos[1]+btn.offsetHeight));},
				transport: "XMLHTTPTransport"
			});

			btn.src = "/qphtml/html/common/ajax_loader.gif";
		}
		catch(e) {
			window.location.reload();
		}
	}
}

function showDocContextMenu(name,url,data,img,imgSrc,x,y)
{
	img.src=imgSrc;
	makeDocContextMenu(name,url,data);
	QP_ContextMenu_show(name,true,x,y);
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// EVENT HANDLERS FOR USER NAME CONTEXT MENUS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function _getPersonMouseImage(elem) {

	
	var img = (elem.nodeName.toUpperCase()=="A") ? elem.nextSibling : elem;
	
	if (img.nodeName.toUpperCase()=="SPAN") {
		return _getPersonMouseImage(img.parentNode);
	} else {
		return img;
	}
	

}
function onPersonMouseOver(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	var img = _getPersonMouseImage(elem);
	
	if (img && img.tagName.toLowerCase()=="img") {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/menu_dropdown.gif");
		img.onclick=function(){onPersonContextMenu(this);return false;}
	}
	e.preventDefault();
}

function onPersonMouseOut(e)
{

	var elem = (e.target) ? e.target : e.srcElement;
	var img = _getPersonMouseImage(elem);
	
	
	if (img && img.tagName.toLowerCase()=="img") {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/clear_pixel.gif");
		img.setAttribute("height", "16");
		img.setAttribute("width", "16");
	}
	e.preventDefault();
}

function onPersonContextMenu(btn)
{
	var a = btn.previousSibling;
	if (a) {
		// this is the doc name anchor
		try {
			// parent node's title attribute is DN
			var dn=QP_ContextMenu_fixName(a.parentNode.title);
			var pos = findPos(btn);
			var imgSrc = btn.src;

			dojo.io.bind ({
				url: a.href + "&Form=h_MemberXml&nowebcaching",
				method: "get",
				mimetype: "text/xml",
				load: function (type, data, evt) {showPersonContextMenu(dn,a.href,data,btn,imgSrc,pos[0],(pos[1]+btn.offsetHeight));},
				transport: "XMLHTTPTransport"
			});

			btn.src = "/qphtml/html/common/ajax_loader.gif";
		}
		catch(e) {
			window.location.reload();
		}
	}
}

function showPersonContextMenu(dn,url,data,img,imgSrc,x,y)
{
	img.src=imgSrc;
	makeUserContextMenu(dn,url,data);
	QP_ContextMenu_show(dn,true,x,y);
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// EVENT HANDLERS FOR MY PLACES CONTEXT MENUS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function onMyPlacesContextMenu(e)
{
	QP_ContextMenu_mouseTracker(e);

	var img = (e.target) ? e.target : e.srcElement;
	var a = img.previousSibling;

	if (a) {
		QP_ContextMenu_show(a.innerHTML + "_MyPlaces");
	}
	e.preventDefault();
}

function onMyPlacesMouseOver(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	var img = (elem.nodeName.toUpperCase()=="A") ? elem.nextSibling : elem;

	if (img) {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/menu_s.gif");
		dojo.event.connect(img, "onmouseup", "onMyPlacesContextMenu");
	}
	e.preventDefault();
}

function onMyPlacesMouseOut(e)
{
	var elem = (e.target) ? e.target : e.srcElement;
	var img = (elem.nodeName.toUpperCase()=="A") ? elem.nextSibling : elem;

	if (img) {
		// this is the context menu icon
		img.setAttribute("src", "/qphtml/html/common/menu_u.gif");
	}
	e.preventDefault();
}


// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// ATTACHMENT MENU ANCHORS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~

var aMSO=[
"EFF75DAA99A1ED99852567B6007121A3",
"E9077196440B29CF852567E500525B7F",
"AA477BBFCF481B9A852567E50055D32C"
];
var D_HTMLPageFormUNID="025BBAB4299CCFDF0525670800167246";

// Generate the <span> containing a document or folder anchor and whatever else is needed
// to associate a context menu with that element.
function GenerateAttachmentsAnchor(unid,name,size,form)
{
	var html="";

	// SPR XHKG76WAJ9: filter unwanted attachments
	if (form==D_HTMLPageFormUNID) {
		// Imported Page: find "real" attachment in list
		var aN = name.split(',');
		var aS = size.split(',');
		for (i=0; i<aN.length; i++) {
			if (aN[i].search(/^TMP[0-9]{2}.*\.[gjch]/i) < 0) {
				name=aN[i];
				size=aS[i];
				break;
			}
		}
	}
	else if (aMSO.indexOf(form) >= 0 && (j=name.indexOf(',')) > 0) {
		// MS Office doc: real attachment is first in list
		name=name.substr(0,j);
		size=size.substr(0,size.indexOf(','));
	}

	if (name.indexOf(',') < 0) {
		// There's only one attachment
		szAlt=size ? QuickrLocaleUtil.getStringResource("CONTEXT.DOWNLOADSIZE").replace("{0}",name).replace("{1}",size) : QuickrLocaleUtil.getStringResource("CONTEXT.DOWNLOAD").replace("{0}",name);
		html = '<a href="../../$defaultview/' + unid + '/$File/' + name + '?OpenElement"'
			+ ' alt="'+szAlt+'" title="'+szAlt+'" target="_blank">'
			+ '<img style="border:none;" src="/qphtml/html/common/download.gif"/>'
			+ '<img class="h-contextMenu-icon" height="16" width="16" '
			+ 'src="/qphtml/html/common/clear_pixel.gif"/>'
			+ '</a>';
	}
	else {
		mName = unid + "_files";
		html = '<span id="'+mName+'" attachments="'+escape(name)+';'+escape(size)+'" class="h-attachments-anchor">'
			+ '<img style="border:none;padding-right:2px;" src="/qphtml/html/common/download.gif"/>'
			+ '<img class="h-contextMenu-icon" '
			+ 'title="' + QuickrLocaleUtil.getStringResource("CONTEXT.ATTACHMENTS") + '" alt="' 
			+ QuickrLocaleUtil.getStringResource("CONTEXT.ATTACHMENTS") 
			+ '" src="/qphtml/html/common/menu_u.gif"/>'
			+ '</span>';
	 }
 	return html;
}

// Generate the menu for a set of attachments.
function makeAttachmentsMenu(name,aNS)
{
	var menu = new QP_ContextMenu(name,"",false);
	if (!menu.exists)
	{
		var unid = name.substring(0,name.indexOf('_'));
		var a = aNS.split(';');
		var aN = unescape(a[0]).split(',');
		var aS = unescape(a[1]).split(',');
		for (i=0; i<aN.length; i++) {
			menu.addItem(aN[i],
							 '../../$defaultview/' + unid + '/$File/' + aN[i] + '?OpenElement',
							 "_blank", null, "/qphtml/html/common/doc_download.gif",
							 QuickrLocaleUtil.getStringResource("CONTEXT.DOWNLOADBYTES").replace("{0}",aS[i]));
		}
		menu.write();
	}
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// USER NAME CONTEXT MENU ANCHORS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Generate the <span> containing a user name anchor (<a> tag) and whatever else is needed
// to associate a context menu with that element.
//
function makeUserNameAnchor(szDN, szCN, szCNPostfixHTML)
{
	var url=getMemberInfoLink(szDN);
	if (url && szCN != '')
	{	
		var memPostfix = szCNPostfixHTML || ''; // Default: no text - e.g., "(Group)" - after name
		// Add a blank before <span> to make it work in Safari. SPR #DYLU7AV623 "Safari UI: banner display problem" 
		return ' <span class="h-user-anchor" title="' + szDN + '">'
			 + '<a href="'+url+'">' + szCN + memPostfix + '</a>'
			 + '<img class="h-contextMenu-icon" height="16" width="16" src="/qphtml/html/common/clear_pixel.gif"/>'
			 + '</span>';
	}
	else {
		return szCN;
	}
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// DOCUMENT & FOLDER CONTEXT MENU ANCHORS
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Duplication of preprocessor #defines, so we can have this code here and not in template
// for now - should probably move back to template (h_ContextMenus.h) eventually.
var D_QPTypeFolder = "1";
var LABEL_YES = "Oui";

// Generate the anchor (<a>) tag for a document, folder, etc.
function GenerateQPObjURLAnchorTag(folderName, qpObjUnid, urlPointer, urlNewWindow, szDocType)
{ 
	var objUrl = GenerateQPObjURLString (folderName, qpObjUnid, urlPointer);

	var aTag = '<a';
	aTag += ' id="' + qpObjUnid + '"'; // NB! Assumes this will never appear twice on the same page!
	aTag += ' href="' + objUrl + '"';

	if (urlNewWindow==LABEL_YES) {
		aTag += ' target="_blank"';
	}
	aTag += '>';

	return (aTag);
}

// Generate the <span> containing a document or folder anchor and whatever else is needed
// to associate a context menu with that element.
function GenerateQPObjURLAnchor(type, aTag, aInner)
{ 
	var span = '<span class=' + (type==D_QPTypeFolder?"h-folder-anchor":"h-doc-anchor") + '>';

	// Add the <a> tag and its inner HTML
	span += (aTag + aInner + '</a>');
	span += '<img class="h-contextMenu-icon" title="' + QuickrLocaleUtil.getStringResource("CONTEXT.OPTIONS") + '" alt="' + QuickrLocaleUtil.getStringResource("CONTEXT.OPTIONS") + '" src="/qphtml/html/common/menu_u.gif"/>';
	span += '</span>';

	return (span);
}


// ~~~~~~~~~~~~~~~~~~~
//
// SIMPLE XML PARSING
//
// ~~~~~~~~~~~~~~~~~~~

// Parse XML containing document-related data.
function getTagValue(xmlDoc, docTag, tag)
{
	try
	{
		//Open the XML Document
		var root = xmlDoc;
		var docs = root.getElementsByTagName(docTag);
		var docTags = docs[0].getElementsByTagName(tag);

		if (docTags.length >= 1) {
			 var val = getNodeValue(docTags[0]);
			 return val;
		}
		else {
			 return "";
		}
	}
	catch (e)
	{
		return "";
	}
}

function getNodeValue (node) {
	if (typeof node.textContent != 'undefined')
	{
		return node.textContent;
	}
	else if (typeof node.innerText != 'undefined')
	{
		return node.innerText;
	}
	else if (typeof node.text != 'undefined')
	{
		return node.text;
	}
	else
	{
		switch (node.nodeType)
		{
			case 3:
			case 4:
				return node.nodeValue;
				break;
			case 1:
			case 11:
				var innerText = '';
				for (var i = 0; i < node.childNodes.length; i++)
				{
					innerText += getNodeValue(node.childNodes[i]);
				}
				return innerText;
				break;
			default:
				return '';
		}
	}
}
/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2008                                    */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/*********************************************************************/

//-------------------------------------------------------------
// Quickplace Drag & Drop library
//-------------------------------------------------------------

function QP_DragAndDrop_makeHandle(unid)
{
	return '<img class="drag-image" id="DH_'+unid+'"'
		+ ' onmouseover="this.origSrc=this.src;this.style.cursor=\'move\';this.src=\'/qphtml/html/common/draghndl_hover.gif\';"'
		+ ' onmouseout="this.src=this.origSrc;this.style.cursor=\'default\';"'
		+ ' src="/qphtml/html/common/drag_icon.gif"'
		+ ' title="' + QuickrLocaleUtil.getStringResource("DND.DRAG") + '" alt="'
		+ QuickrLocaleUtil.getStringResource("DND.DRAG") + '"/>';
}

var h_bInsideDragSource = false;
//------------------------------------------------------------------------------------
// Tag to mark the beginning of a drag source area.
//
function QP_DragAndDrop_makeContainer(tag, unid, cName)
{
	var c=((cName===undefined || cName=="") ? "" : " class=\""+cName+"\"");
	return '<'+tag+' id="DC_'+unid+'"'+c
		 + ' onmouseover="this.className=\'h-dragSource-selected\'; document.getElementById(\'DH_'+unid+'\').style.visibility=\'visible\';"'
		 + ' onmouseout="this.className=\'h-dragSource-deselected\'; document.getElementById(\'DH_'+unid+'\').style.visibility=\'hidden\';"'
		 + '>';
}

function QP_DragAndDrop_sourceBegin(tag, unid, nC, lev)
{
	var html="";

	// Do not make a doc with response(s) draggable unless manager
	if (UIDragAndDropIsEnabled() && lev==1 && currentUserAccess>2) {

		// Terminate preceeding drag source first
		html += QP_DragAndDrop_sourceEnd(tag);

		if (!(currentUserAccess<6 && nC>0))
		{
			h_bInsideDragSource = true;
			html += QP_DragAndDrop_makeContainer(tag, unid);
		}
	}
	return html;
}

//------------------------------------------------------------------------------------
// Tag to mark the end of a drag source area.
//
function QP_DragAndDrop_sourceEnd(tag)
{ 
	var html="";
	if (h_bInsideDragSource) {
		h_bInsideDragSource = false;
		html += ("</" + tag + ">");
	}
	return html;
}


//------------------------------------------------------------------------------------
// Create all objects needed for drag & drop
//
function QP_DragAndDrop_createObjects(tag, szContainerId)
{
	if (UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		QP_DragAndDrop_initDragSources(tag, szContainerId);
//		QP_DragAndDrop_initDropTargets("toc", "div");
		QP_DragAndDrop_createForm();
	}
}

//------------------------------------------------------------------------------------
// Initialize all drag sources
// within a containing table whose id is szContainerId.
//
function QP_DragAndDrop_initDragSources(tag, szContainerId)
{

	var dl = document.getElementById(szContainerId);
	if (dl != null && UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		var dragList =  qp_getElementsByClassName("h-dragSource", "*", dl);

		for (var i=0; i < dragList.length; i++)
		{
			var ds = new dojo.dnd.HtmlDragSource(dragList[i], "dojoDragList");

			var unid = dragList[i].id.substring(8); // FIX ME: magic number
			var dh = document.getElementById("DH_"+unid);
			if (dh) {
				dojo.html.disableSelection(dh);
				ds.setDragHandle(dh);
			}

			dojo.event.connect(ds, "onDragEnd", function(e) {

				// Get enclosing drag source element
				if (e.dragObject && e.dragStatus == "dropSuccess") {
					// dragged it to a drop target
					var dragNode = e.dragObject.domNode;
					if (dragNode) {
						var parent = dragNode.parentNode;
						var srcUnid = dragNode.id.substring(8); // FIX ME: magic number

						// alert("onDragEnd: " + "\ndropped " +  dragNode.id + " to " + parent.id);
						QP_DragAndDrop_copyMove(srcUnid, parent.id, "1");
							  
						dojo.dom.removeNode(dragNode);
						var dc = document.getElementById("DC_"+srcUnid);
						if (dc) {
							// Remove container of draggable content
							dojo.dom.removeNode(dc);
						}
					}
				}
				//else {
				// Invalid drop
				// alert("drag object="+e.dragObject+"\nstatus="+e.dragStatus);
				//}
			});
		}
	}
}

//------------------------------------------------------------------------------------
// Initialize all drop targets with tag szTag,
// within a containing tag whose id is szContainerId.
//
function QP_DragAndDrop_initDropTargets(szContainerId, szTag)
{
	var container = document.getElementById(szContainerId);
	if (container != null && UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		var dropList = container.getElementsByTagName(szTag);

		for (var i=0; i < dropList.length; i++) 
		{
			if (dropList[i].className.indexOf("dropTarget") >= 0) 
			{
				// Don't make CURRENT or Index folder a drop target
				if (dropList[i].id != h_FolderStorage && dropList[i].id != "h_Index") {

					var dt = new dojo.dnd.HtmlDropTarget(dropList[i], ["dojoDragList"]);

					// FIX ME BRR:
					// It would be nice to change the folder icon when dragged over,
					// but these Dojo events don't reliably return the id of the
					// element being dragged over, so can't do this for now.

// 					dojo.event.connect(dt, "onDragOver", function(e) {

// 						console.log(e.target.tagName);
// 						if (e.target.tagName.toLowerCase() == "div") {
// 							var imgs = e.target.getElementsByTagName("img");
// 							if (imgs[0]) {
// 								imgs[0].src = "/qphtml/html/common/folder_selected.gif";
// 							}
// 						}							
// 						else if (e.target.tagName.toLowerCase() == "img")
// 							e.target.src = "/qphtml/html/common/folder_selected.gif";
// 					});
						
// 					dojo.event.connect(dt, "onDragOut", function(e) {
// 						console.log(e.target.tagName);
// 						if (e.target.tagName.toLowerCase() == "img")
// 							e.target.src = "/qphtml/html/common/folder_close.gif";
// 					});
				}
			}
		}
	}
}

//------------------------------------------------------------------------------------
// Initialize a single drop target
//
function QP_DragAndDrop_initDropTarget(obj)
{
	if (UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		new dojo.dnd.HtmlDropTarget(obj, ["dojoDragList"]);
	}
}

// --------------------------------------------------
// Copy or move a doc to a folder
// Change to a "wait" cursor until response received.
//
function QP_DragAndDrop_copyMove(srcUnid, destUnid, bMoveIt)
{
	var copyOrMove = (bMoveIt ? "1" : "0");
	var form = document.getElementById("copyMoveForm");
	if (form) {

		form.action = getAbsoluteRoomURL(self) + '/' + h_FolderStorage + '/' + srcUnid + '/?EditDocument';

		form.h_Move.value = copyOrMove;
		form.h_DestRoomNsfName.value = currentRoom.roomNsf;
		form.h_DestFolderUNID.value = destUnid;
		form.h_SetDeleteList.value = srcUnid;
		form.h_HandleResponses.value = "1";

		QPAjax_SubmitForm("copyMoveForm", sFunc, eFunc);
	}
}

function sFunc(data)
{
}

// This is sidHaikuPagesNotMoved from nquickplacers.rc.
function eFunc(data)
{
	alert(QuickrLocaleUtil.getStringResource("DND.ERROR"));
	location.reload();
}



// --------------------------------------------------
// Create the form used to submit an asynch request
// to copy or move a doc to a folder
//
function QP_DragAndDrop_createForm()
{
	// Add form to copy/move docs to this page
	var form = document.createElement("form");
	form.id = "copyMoveForm";
	form.method = "POST";
	form.name="h_CopyMoveForm";
	 
	var html = "";
	html += '<input type="hidden" name="h_EditAction" value="h_Ajax">';
	html += '<input type="hidden" name="h_Move">';
	html += '<input type="hidden" name="h_HandleResponses" value="0">';
	html += '<input type="hidden" name="h_AllDocs" value="">';
	html += '<input type="hidden" name="h_DestRoomNsfName" value="">';
	html += '<input type="hidden" name="h_DestFolderUNID" value="">';
	html += '<input type="hidden" name="h_SetPublishAboveTocEntry" value="">';
	html += '<input type="hidden" name="h_SetDeleteList" value="">';
	html += '<input type="hidden" name="h_SetCommand" value="h_MoveCopyPages">';
	html += '<input type="hidden" name="h_NoSceneTrail" value="1">';
	 
	form.innerHTML = html;
	document.body.appendChild(form);
}		
/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2008                                    */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/*********************************************************************/

//-------------------------------------------------------------
//  Quickplace common folder display functions
//-------------------------------------------------------------

dojo.require("dojo.dateIslamic");
dojo.require("dojo.dateHebrew");

function returnSaveDateTime(date){
	return convertDate(date) + " " + convertTime(date);
}

function convertDate(date){
	var ret = "";
	var sep = haiku.h_Intl_DateString;
	var year = date.getFullYear();

	if(isHijri){
			date = new dateHijri().gregorianToHijri(date);
			year = date.getFullYear();
		}
	if(isHebrew){
				date = new dateHebrew().gregorianToHebrew(date);
				year = date.getFullYear();
			}
	
	var month =(((date.getMonth()+1) < 10) ? "0" : "") + (date.getMonth()+1);
	var day =((date.getDate() < 10) ? "0" : "") + date.getDate();
	if(haiku.h_Intl_DateFormat == haiku.kszDMY) {
		ret = day + sep + month + sep + year;
	}else if(haiku.h_Intl_DateFormat == haiku.kszYMD){
		ret = year + sep + month + sep + day;
	}else{
		ret = month + sep + day + sep + year;
	}
	return ret;
}

function convertTime(date){
	var ret = "";
	var am_pm = "";
	var hrs = date.getHours();
	var mins = date.getMinutes();
	var mins = ((mins < 10) ? "0" : "") + mins;
	if(!haiku.h_Intl_MilitaryTime){
		am_pm = ((hrs >= 12) ? ' ' + haiku.h_Intl_PMString : ' ' + haiku.h_Intl_AMString);
		hrs  = ((hrs > 12) ? hrs - 12 : hrs);
		if(hrs == 0) hrs = 12;
	}
	return (hrs + haiku.h_Intl_TimeString + mins + am_pm);
}

//------------------------------------------------------------------------------------

var fResponseImgTag ='<img src="/qphtml/html/common/response%a.gif" style="padding-right:0.5em;vertical-align:middle;"/>';

function fResponseImg(bAtt)
{
	return (bAtt ? fResponseImgTag.replace(/%a/,'-attach') : fResponseImgTag.replace(/%a/,''));
}

//------------------------------------------------------------------------------------
// Abstract (Summary) View
//
var nRow=0;
function DisplayAbstractViewEntry(chkbx,type,name,unid,aName,auth,authDN,crDate,lastEd,lastEdDN,modDate,szAbstract,form,hasP,nC,lev,revNum,attName,attSize,isLocked,docNum,nDD)
{
	nRow++;

	var ALTTEXT_HIDEMEMBERS = QuickrLocaleUtil.getStringResource("FOLDER.HIDEMEMBERS"); 
	var m_UPDATETEXT = QuickrLocaleUtil.getStringResource("FOLDER.UPDATEDBY");
	var m_DATETIMEPROCESS = QuickrLocaleUtil.getStringResource("FOLDER.DATETIME"); //{0} is the date, {1} is the time
	var m_DATEPROCESS = QuickrLocaleUtil.getStringResource("FOLDER.DATE"); //{0} is the date/time

	var MSG_ABSTRACT_UPDATED = QuickrLocaleUtil.getStringResource("FOLDER.UPDATED");
	var MSG_ABSTRACT_CREATED = QuickrLocaleUtil.getStringResource("FOLDER.CREATED");

	//format the dates appropriately
	var cDate = crDate;
	var mDate = modDate;

	var arr_cDate = new Array();
	var arr_mDate = new Array();
	var sProcess = "";
	
	
	//if there is a space, then separate the date from the time and format it...
	if (cDate.indexOf(" ") == -1) {
		arr_cDate[0] = cDate;
		sProcess = m_DATEPROCESS;
	} else {
		arr_cDate[0] = cDate.substring(0, cDate.indexOf(" ") );
		arr_cDate[1] = cDate.substring(cDate.indexOf(" ") + 1 );
		sProcess = m_DATETIMEPROCESS;
	}
	
	if(isHijri){ 
		var hcDate = new dateHijri().gregorianToHijri(new Date(cDate));
		
		var dateString = "";
        var sep = haiku.h_Intl_DateString;
		if (haiku.h_Intl_DateFormat == haiku.kszDMY) 
        {
            dateString = hcDate.getDate() + sep + (hcDate.getMonth()+1) + sep + hcDate.getFullYear();
        }
        else if (haiku.h_Intl_DateFormat == haiku.kszYMD) 
        {
            dateString = hcDate.getFullYear() + sep + (hcDate.getMonth()+1)+ sep + hcDate.getDate();
        }
        else 
        {
            dateString = (hcDate.getMonth()+1) + sep + hcDate.getDate() + sep + hcDate.getFullYear();
        }

		arr_cDate[0] = dateString;
	}	
	if(isHebrew){
		var hcDate = new dateHebrew().gregorianToHebrew(new Date(cDate));
		
		var dateString = "";
        var sep = haiku.h_Intl_DateString;
		if (haiku.h_Intl_DateFormat == haiku.kszDMY) 
        {
            dateString = hcDate.getDate() + sep + (hcDate.getMonth()+1) + sep + hcDate.getFullYear();
        }
        else if (haiku.h_Intl_DateFormat == haiku.kszYMD) 
        {
            dateString = hcDate.getFullYear() + sep + (hcDate.getMonth()+1) + sep + hcDate.getDate();
        }
        else 
        {
            dateString = (hcDate.getMonth()+1) + sep + hcDate.getDate() + sep + hcDate.getFullYear();
        }

		arr_cDate[0] = dateString;
	
	}
	
	cDate = AbstractStringProcess(sProcess, arr_cDate );
	
	if (mDate.indexOf(" ") == -1) {
		arr_mDate[0] = mDate;
		sProcess = m_DATEPROCESS;
	} else {
		arr_mDate[0] = mDate.substring(0, mDate.indexOf(" ") );
		arr_mDate[1] = mDate.substring(mDate.indexOf(" ") + 1 );
		sProcess = m_DATETIMEPROCESS;
	}
	
	if(isHijri){ 
		var hmDate = new dateHijri().gregorianToHijri(new Date(mDate));
		
		var dateString = "";
        var sep = haiku.h_Intl_DateString;
		if (haiku.h_Intl_DateFormat == haiku.kszDMY) 
        {
            dateString = hmDate.getDate() + sep + (hmDate.getMonth()+1) + sep + hmDate.getFullYear();
        }
        else if (haiku.h_Intl_DateFormat == haiku.kszYMD) 
        {
            dateString = hmDate.getFullYear() + sep + (hmDate.getMonth()+1) + sep + hmDate.getDate();
        }
        else 
        {
            dateString = (hmDate.getMonth()+1) + sep + hmDate.getDate() + sep + hmDate.getFullYear();
        }

		arr_mDate[0] = dateString;
	}	
	if(isHebrew){

				var hmDate = new dateHebrew().gregorianToHebrew(new Date(mDate));
						var dateString = "";
        var sep = haiku.h_Intl_DateString;
		if (haiku.h_Intl_DateFormat == haiku.kszDMY) 
        {
            dateString = hmDate.getDate() + sep + (hmDate.getMonth()+1) + sep + hmDate.getFullYear();
        }
        else if (haiku.h_Intl_DateFormat == haiku.kszYMD) 
        {
            dateString = hmDate.getFullYear() + sep + (hmDate.getMonth()+1) + sep + hmDate.getDate();
        }
        else 
        {
            dateString = (hmDate.getMonth()+1) + sep + hmDate.getDate() + sep + hmDate.getFullYear();
        }

		arr_mDate[0] = dateString;
	
	}
	
	mDate = AbstractStringProcess(sProcess, arr_mDate );
	
	if (typeof(h_TextAbstract) != "undefined" && h_TextAbstract == "0")
		szAbstract = "";

	var szEnd="";
	var szClass="";

	if (isLocked=="1") {
		szClass=' class="row-locked"';
		szEnd='<img title="'+auth+'" alt="'+auth+'" src="/qphtml/html/common/lockme_page_curl.gif"/>';
	}
	else if (nRow % 2 == 0)
		szClass=' class="row-alternate"';

	if (attName != 0)
		szEnd += GenerateAttachmentsAnchor(unid,attName,attSize,form);

	var entry='';
	var divT='';
	// DND allowed only if:
	// - Top level doc (children will be dragged with it)
	// - Not a folder
	// - DND enabled on server
	// - Access level > Reader, or >= Manager if doc has children
	//
	if (lev=="1" && type!="1" && (UIDragAndDropIsEnabled() && currentUserAccess>2 && !(nC>0 && currentUserAccess<6))) {
		entry='<dl class="h-abstractEntry" id="DC_'+unid+'"'
		 + ' onmouseover="document.getElementById(\'DH_'+unid+'\').style.visibility=\'visible\';"'
		 + ' onmouseout="document.getElementById(\'DH_'+unid+'\').style.visibility=\'hidden\';">'
		divT='<div class="h-abstractEntryTitle h-dragSource" id="dragSrc_'+unid+'">'+QP_DragAndDrop_makeHandle(unid);
	}
	else {
		//can't drag folders or responses
		entry='<dl class="h-abstractEntry">';
		divT='<div class="h-abstractEntryTitle">';
	}

	var divR='';
	if (nDD != "0") {
		 var img = '<img class="twisty" id="TW_'+unid+'"'
			  + ' src="/qphtml/html/common/treenode_expand_plus.gif"'
			  + ' onclick="javascript:___getResponses(this,\''+docNum+'\',\''+nDD+'\',\''+unid+'\');"/>';

		divR='<div class="h-abstractEntryResponses">'
			 + img + fResponseImg(attName!='') + nDD + ' réponses'
			 + '<div id="RD_'+unid+'">';
			 + '</div>';
			 + '</div>';
	}

	var upd = MSG_ABSTRACT_UPDATED;
	upd = upd.replace("{0}", mDate);
	upd = upd.replace("{1}", ((lastEdDN == '' && lastEd =='') ? '' : GetMemberProfileName(lastEdDN,lastEd)));
	
	var crt = MSG_ABSTRACT_CREATED;
	crt = crt.replace("{0}", cDate);
	var html = entry
		 + ' <table width="100%" cellpadding="0" cellspacing="0">'
		 + '  <tr' + szClass + '>'
		 + '   <td class="start" width="10">' + chkbx + '</td>'
		 + '   <td class="icon" width="35"><img class="h-abstractEntryIcon" src="' + GetDocTypeIconImgSrc(type, form, null, 'LG') + '"/></span></td>'

		 + '   <td class="body">'
		 +      divT
		 +       (typeof(aName) != 'undefined' ? GenerateQPObjURLAnchor(type,aName,name) : name)
		 + '    </div>'

		 + '    <div class="h-abstractEntryText">'
		 + upd + ' | ' + crt
		 + '    </div>'
		 + '    <div class="h-abstractEntryDetail">'+szAbstract+'</div>'

		 +      divR

		 + '   </td>'
		 + '   <td class="end" width="42" valign="top">'+szEnd+'</td>'
		 + '  </tr>'
		 + ' </table>'
		 + '</dl>';
	
	document.write(html);
}

function ___getResponses(twisty,docNum,cnt,unid)
{
	if (twisty.src.indexOf("minus.gif")>0) {
		var divR=document.getElementById('RD_'+unid);
		divR.innerHTML = "";
		divR.style.display="none";
		twisty.src="/qphtml/html/common/treenode_expand_plus.gif";
	}
	else {
		var url=location.href;
		var i=url.indexOf('&');
		if (i>0)
			url=url.substring(0,i);
		url+='&ExpandView&Start='+docNum+'.1&Count='+cnt+'&Form=h_FolderViewJSON&nowebcaching';
		  
		try {
			dojo.io.bind({
				url: url,
				method: "get",
				load: function(type, data, evt){___showResponses(data,unid)},
				error: function(type, error){___nothing()},
				mimetype: "text/javascript",
				transport: "XMLHTTPTransport"
			});
		}
		catch(e) {
			this.Error(e);
		}
	}
}

function ___showResponses(data,unid)
{
	try {
		var html = "";
		var items = data.items;
		for (i = 0; i < items.length; i++)
		{
			var item=items[i].item;

			html+=FV.responses.SimpleResponseIndent(item.DocLevel,item.HasChildren,item.Attachments)
				 +GenerateQPObjURLAnchor(item.Type,
												 GenerateQPObjURLAnchorTag(data.FolderStorage,item.Unid,item.URLpointer,item.URLNewWindow, item.Type),
												 item.Name)
				 +'<br/>';
		}

		var divR=document.getElementById('RD_'+unid);
		divR.innerHTML = html;
		QP_ContextMenu_attachMenus(divR);
		divR.style.display="block";

		var imgT=document.getElementById('TW_'+unid);
		imgT.src="/qphtml/html/common/treenode_expand_minus.gif";
	}
	catch (e) {
	}
}

function ___nothing(e){}

function AbstractStringProcess(sFormat, arrValues)
{
	var sReturn = sFormat;

	for (var i = 0; i < arrValues.length; i++) {
		var sTmp = "{" + i + "}";

		while (sReturn.indexOf(sTmp) > -1) {
			sReturn = sReturn.replace(sTmp, arrValues[i]);
		}
	}

	return sReturn;
}

//------------------------------------------------------------------------------------
// 

function DisplayMyPlacesBegin()
{
	document.write('<table width="100%"><tbody>');
}

function DisplayMyPlacesEnd()
{
	document.write('</tbody></table>');
}

function DisplayMyPlacesEntry(url,name,title,desc,size,accDate,modDate,ownerDNs,ownerCNs,ownerEms,isLocked)
{
	var target = (G_bOpenPlacesInNewWindow ? ' target="_blank"' : '');
	var ownerHtml = "";

	var aCN = new Array();
	if (typeof(ownerCNs) != "undefined" && ownerCNs != "") {
		aCN = ownerCNs.split(",");
	}

	var aEm = new Array();
	if (typeof(ownerEms) != "undefined" && ownerEms != "") {
		aEm = ownerEms.split(",");
	}

	// DNs for ST awareness
	// Currently unavailable in proper format
// 	var aDN = new Array();
// 	if (typeof(ownerDNs) != "undefined" && ownerDNs != "") {
// 		aDN = ownerDNs.split(";");
// 	}

	for (var i=0; i<aCN.length; i++) {

		if (aCN[i].toLowerCase != "unknown") {

			// LDAP name awareness if ST enabled
// 			var bLocal=(aDN[i].indexOf("/OU=QP/")>0);
// 			if (!bLocal) {
// 				ownerHtml += GetSTAwarenessIcon("",aCN[i],aDN[i]);
// 			}

			if (i<aEm.length && aEm[i].toLowerCase != "unknown") {
				// got email address
				var href = "mailto:"+aEm[i];
				if (G_ProfileServer != "") {
					// support Javlin card
					ownerHtml += qp_makeJavlinName(aCN[i],aCN[i],href,aEm[i],false);
				}
				else {
					ownerHtml += '<a href="'+href+'">'+aCN[i]+'</a>';
				}
			}
			else {
				ownerHtml += aCN[i];
			}
			 
			if ((i+1) < aCN.length) {
				ownerHtml += ", ";
			}
		}
	}

	// FIX ME: Still need to re-style for One UI look, but this'll do for now:
	var html= '<tr><td valign="top" width="100%">'
	+ '<div class="entry" onmouseout="this.style.background=\'#fff\';this.style.cursor=\'default\';" onmouseover="this.style.background=\'#eaf2fe\';this.style.cursor=\'hand\';" style="background: rgb(255, 255, 255) none repeat scroll 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;">'
	+ '  <span>'
	+ '   <a class="lotusPerson" href="'+url+name+'"'+target+'>'
	+ '    <h4>'+title+'</h4>'
	+ '    <div class="entryDetails">'
	+ '     <p>'+desc+'</p>'
	+ '    </div>'
	+ '   </a>'
	+ '  </span>'
	+ '  <div class="entryDetails">'
	+ '   <span class="outer">'
	+ '    <span class="person">'
	+ '     Propriétaire :&nbsp;'
	+ '    </span>'
	+      ownerHtml
	+ '   </div>'
	+ ' </div>'
	+ '</td></tr>';

	document.write(html);
}


//-----------------------------------------------------------------
// FUNCTIONS USED TO IMPLEMENT FOLDER SCENE SKIN COMPONENTS

function FolderItemsPerPageLink(n, szN, szTitle)
{
	var cnt = h_FolderNavBaseURL.indexOf("&Count="); 
	var url = h_FolderNavBaseURL.substring(0, cnt+7);
	 
	document.write('<a '
						+ '" alt="' + szTitle + '" title="' + szTitle 
						+ '" href="' + url + n
						+ '&PresetFields=h_SetReadScene;' + h_SetReadScene
						+ '">' + szN + '</a>');
}

var h_F_MyPlacesParms = new Array("&PresetFields=h_SetReadScene;h_MyPlacesList","&PresetFields=h_SetReadScene;h_MyPlacesDetails");

function FolderShowHideDetailsLink(szShow, szHide, szShowTitle, szHideTitle)
{
	var fS = getFolderStyle();
	if (fS == 'h_MyPlaces') {
		// My Places listing
		var loc = location.href;
		var l=m=n=-1;

		// Get which parm if any, and parm's length
		for (var i=0; i<h_F_MyPlacesParms.length; i++) {
			if ((m=loc.indexOf(h_F_MyPlacesParms[i])) != -1) {
				l=h_F_MyPlacesParms[i].length;
				break;
			}
		}

		if ((n=m+l)>0) {
			// Strip param from current URL
			loc = loc.substring(0, m) + loc.substring(n);
		}

		document.write('<a href="'
							+ loc + '&PresetFields=h_SetReadScene;'
							+ '&PresetFields=h_SetReadScene;'
							+ (h_SetReadScene == 'h_MyPlacesList' ? 'h_MyPlacesDetails' : 'h_MyPlacesList')
							+ '"'
							+ ' title="' + (h_SetReadScene == 'h_MyPlacesDetails' ? szHideTitle : szShowTitle) + '"'
							+ ' alt="'   + (h_SetReadScene == 'h_MyPlacesDetails' ? szHideTitle : szShowTitle) + '"'
							+ '>'
							+ (h_SetReadScene == 'h_MyPlacesDetails' ? szHide : szShow)
							+ '</a>');
	}
	else {
		// Folder listing
		document.write('<a href="'
							+ '../../h_Toc/' + h_FolderDoc.h_Unid + '/?OpenDocument&Start=' + h_FolderStart
							+ '&Count=' + (h_SetReadScene == 'h_AbstractsFolderRead' ? 20 : 10)
							+ '&PresetFields=h_SetReadScene;'
							+ (h_SetReadScene == 'h_AbstractsFolderRead' ? 'h_StdFolderRead' : 'h_AbstractsFolderRead')
							+ '"'
							+ ' title="' + (h_SetReadScene == 'h_AbstractsFolderRead' ? szHideTitle : szShowTitle) + '"'
							+ ' alt="'   + (h_SetReadScene == 'h_AbstractsFolderRead' ? szHideTitle : szShowTitle) + '"'
							+ '>'
							+ (h_SetReadScene == 'h_AbstractsFolderRead' ? szHide : szShow)
							+ '</a>');
	}
}

// Same as above, for 8.1 theme
function qp_folder_SetView(details)
{
	location.href='../../h_Toc/'+h_FolderDoc.h_Unid+'/?OpenDocument&Start='+h_FolderStart
		+ '&Count='+(details ? 10 : 20)
		+ '&PresetFields=h_SetReadScene;'
		+ (details ? 'h_AbstractsFolderRead' : 'h_StdFolderRead');
}

function FolderShowHideResponsesLink(szShow, szHide, szShowTitle, szHideTitle)
{
	if (h_SetReadScene != 'h_AbstractsFolderRead') {
		var i = location.href.indexOf("&Collapse");
		var bShow = (i > -1);
		document.write('<a href="' + (bShow ? location.href.substring(0,i) : location.href+"&CollapseView") + '"'
							+ ' title="' + (bShow ? szShowTitle : szHideTitle) + '"'
							+ ' alt="'   + (bShow ? szShowTitle : szHideTitle) + '"'
							+ '>'
							+ (bShow ? szShow : szHide)
							+ '</a>');
	}
}

function FolderShowingItemsText(szFmt) 
{ 
	if (h_FolderDocCount > 0)
	{
		var s = szFmt;
			  
		var iEndIndex =  h_FolderStart.indexOf( ".");
		if	( iEndIndex == -1) {
			iEndIndex = h_FolderStart.length;
		}
		 
		// The thread start (1 in the above string
		var iThreadStart = h_FolderAbsoluteStartPosition;
		// The last thread in the list
		var rangeEnd = h_FolderAbsoluteStartPosition + iTotNumOfDocs - 1;
		 
		// replace the string which has the following syntax	
		s = s.replace( /\%d/, iThreadStart);
		s = s.replace( /\%d/, rangeEnd);
		s = s.replace( /\%d/, h_FolderDocCount);
		document.write(s);
	}
};


//------------------------------------------------------------------------------------
// Return next folder sort URL and alt text as an array
//
function GetFolderSortUrlAlt(title, pos)
{
	var ALT_LINK_SORTBY = QuickrLocaleUtil.getStringResource("FOLDER.SORTBY");
	var ALT_LINK_SORTASCENDING = QuickrLocaleUtil.getStringResource("FOLDER.SORTASCENDING");
       	var ALT_LINK_SORTDESCENDING = QuickrLocaleUtil.getStringResource("FOLDER.SORTDESCENDING");
	var ALT_LINK_SORTDEFAULT = QuickrLocaleUtil.getStringResource("FOLDER.SORTDEFAULT");
	var newLoc;
	
	if ( typeof ( h_FolderNavBaseURL) != "undefined" && h_FolderNavBaseURL != "") {
		newLoc = getAbsoluteServerRootPath(self) + h_FolderNavBaseURL;
	} else  {
		newLoc = location.href;
	}
	var idx, idx1;
	// nCurColSort==-1 if there is no sorted column.  Otherwise it will be the number of the col that is sorted.
	var nCurColSort = -1;
	// nColSortType==0 for none, 1 for ascending, and 2 for descending
	var nColSortType = 0;
	var szAlt="";

	idx = newLoc.indexOf("&ResortAscending=");
	if (idx != -1)
	{
		nColSortType = 1;
		// get rid of the &ResortAscending= parm
		idx1 = newLoc.indexOf ("&", idx+1);
		if (idx1 != -1) 
		{
			nCurColSort = newLoc.substring(idx + 17, idx1);
			newLoc = newLoc.substring(0, idx) + newLoc.substring(idx1);
		}
		else
		{
			nCurColSort = newLoc.substring(idx + 17);
			newLoc = newLoc.substring(0, idx);
		}
	}

	idx = newLoc.indexOf("&ResortDescending=");
	if (idx != -1)
	{
		nColSortType = 2;
		// get rid of the &ResortDescending= parm
		idx1 = newLoc.indexOf ("&", idx+1);
		if (idx1 != -1) 
		{
			nCurColSort = newLoc.substring(idx + 18, idx1);
			newLoc = newLoc.substring(0, idx) + newLoc.substring(idx1);
		}
		else
		{
			nCurColSort = newLoc.substring(idx + 18);
			newLoc = newLoc.substring(0, idx);
		}
	}

	idx = newLoc.indexOf ("&Start=");
	if (idx != -1) {
		// remove &Start=xx and replace it with &Start=1
		idx1 = newLoc.indexOf ("&", idx+1);
		newLoc = newLoc.substring(0, idx) + "&Start=1" + (idx1 != -1 ? newLoc.substring(idx1) : '');
	}

	idx = newLoc.indexOf ("&StartAtLastPage");
	if (idx != -1) {
		// remove &StartAtLastPage and replace it with &Start=1
		idx1 = newLoc.indexOf ("&", idx+1);
		newLoc = newLoc.substring(0, idx) + "&Start=1" + (idx1 != -1 ? newLoc.substring(idx1) : '');
	}

	if (nCurColSort != pos) {
		// Currently not sorted on THIS column
		szAlt = ALT_LINK_SORTBY + title + ALT_LINK_SORTASCENDING;
		newLoc += '&ResortAscending=' + parseInt(pos);
	}
	else {
		// Currently sorted on this column; changing order
		if (nColSortType == 1) {
			// current column is sorted Ascending so next sort type is Descending
			newLoc += '&ResortDescending=' + parseInt(pos);
			szAlt = ALT_LINK_SORTBY + title + ALT_LINK_SORTDESCENDING;
		}
		else {
			// current column is sorted Descending so next sort type is none
			szAlt=	ALT_LINK_SORTDEFAULT;
		}
	}
	return [newLoc,szAlt];

} // GetFolderSortUrlAlt


//------------------------------------------------------------------------------------
// Generate Sort button
//

function DisplaySortAction(title, pos)
{ 
	var szClass='';
	var aStyle=' style="display: none;"';
	var dStyle=aStyle;
	var urlAlt = GetFolderSortUrlAlt(title, pos);

	if (urlAlt[0].indexOf("&ResortAscending=")>0) {
		// current sort is none
		szClass= '';
	}
	else if (urlAlt[0].indexOf("&ResortDescending=")>0) {
		// current sort is ascending
		dStyle='';
		szClass='class="sortButton"';
	}
	else {
		// current sort is descending
		aStyle='';
		szClass='class="sortButton"';
	}

	document.write ('<li '+szClass+'>'
			  + '<a href="'+urlAlt[0]+'" alt="'+urlAlt[1]+'" title="'+title+'">'+title
			  + '<span'+aStyle
			  + '<img title="ascending" alt="'+urlAlt[1]+'" src="/qphtml/html/common/sort_ascending.gif"/>'
			  + '</span>'
			  + '<span'+dStyle
			  + '<img title="descending" alt="'+urlAlt[1]+'" src="/qphtml/html/common/sort_descending.gif"/>'
			  + '</span>'
			  + '</a>'
			  + '</li>');
}

function DisplaySortBarBegin(szSortBy)
{
	var sEntry = "";

	if (typeof(Quickr81SupportUtil) != "undefined" || h_SetReadScene=="h_MyPlacesList") {
		sEntry += '<div class="lotusSort">'
			 + '<ul class="lotusInlinelist">'
			 + '<li class="lotusFirst">' + QuickrLocaleUtil.getStringResource("FOLDER.SORTBY") + '</li>';
	}
	else {
		sEntry += "<div class=\"actions sort\">";
		sEntry += "	<ul class=\"inlinelist\">";
		sEntry += "  <li class=\"first\">"+szSortBy+":</li>";
	}
	// Other <li>s for sort items come after this...
	document.write(sEntry);
}

function DisplaySortBarEnd()
{
	var sEntry = "";
	sEntry += " </ul>";
	sEntry += "</div>";
	document.write(sEntry);
}

function DisplayAbstractViewSortBegin(chkbx,szSortBy/*add other strings*/) 
{
	var sEntry = "";
	sEntry += "<dl class=\"h-abstractEntry\"><table width=\"100%\" cellpadding=\"10\"><tr>";
	sEntry += "	<td width=\"10\">" + chkbx + "</td>";
	sEntry += "	<td width=\"*\">";
	document.write(sEntry);
	DisplaySortBarBegin(szSortBy);
}

function DisplayAbstractViewSortEnd()
{
	var sEntry = "";
	DisplaySortBarEnd();
	sEntry += "	</td>";
	sEntry += "</tr></table></dl>";
	document.write(sEntry);
}


//------------------------------------------------------------------------------------
//

function FolderHideIdIfBlank(sId, fFunct) {
	var preloadid = document.getElementById(sId);
	if (preloadid) {
	
		var bHide = true;
		for (var i = 0; i < preloadid.childNodes.length; i++) {
			if (typeof(preloadid.childNodes[i].tagName) != "undefined" && typeof(preloadid.childNodes[i].innerHTML) != "undefined" && preloadid.childNodes[i].tagName != "SCRIPT") {
				bHide = false;
			}
			if (typeof(fFunct) != "undefined") {
				if (fFunct() == "") {
					bHide = true;
				}
			}
		}
		
		if (bHide) {
			preloadid.style.display = "none";
		}
	}
}

function FolderAlternateTableRowsBackground(sId, sClassName) {
	if (sClassName == null) sClassName = "h-folderitem-bg";
	var mydetailslist = document.getElementById(sId);
	if (mydetailslist) {
		var onoffswitch = false;
		var alltrs = mydetailslist.getElementsByTagName("tr");
		for (var idx = 0; idx < alltrs.length; idx++) {
			if (alltrs[idx].className.toLowerCase() == sClassName.toLowerCase()) {
				if (onoffswitch) {				
					alltrs[idx].className += " h-folderItem-bg-alt";
				}
				onoffswitch = !onoffswitch;
			}
		}
	}
}

// "Stretch" button support
function changeWidth(widthSet)
{
	var cookieName = haiku.userName  +'Width';
	if(widthSet=="fluid"){
		document.body.style.width=100+'%';
		document.getElementById("widthPage").style.display="none";
		document.getElementById("widthPageFixed").style.display="inline";
		setCookie(cookieName,'fluid',7);
	}
	else {
		document.body.style.width=900+'px';
		document.getElementById("widthPageFixed").style.display="none";
		document.getElementById("widthPage").style.display="inline";
		removeCookie(cookieName);
		  
		var mainSize = document.getElementById("portletRenderWidth").offsetWidth;
		var bodySize = document.body.offsetWidth;
		if(mainSize>bodySize){
			document.body.style.width = mainSize +50+'px';
		}
	}
}

// IBM Footer
function toggleFooter() {
	var footerL = document.getElementById('footerMain');
	var footerS = document.getElementById('footerSmall');

	if (footerL.style.display == "none"){
		footerS.style.display="none";
		footerL.style.display="block";
		document.getElementById("footerLinkIDExpand").style.display='none';
		document.getElementById("footerLinkIDCollapse").style.display='block';
	}
	else{
		footerL.style.display="none";
		footerS.style.display="block";
		document.getElementById("footerLinkIDExpand").style.display='block';
		document.getElementById("footerLinkIDCollapse").style.display='none';
	}

	var cookieName = haiku.userName +'Footer';
	var x = getCookie(cookieName);
	if (x=="small") {
		removeCookie(cookieName);
	}else{
		setCookie(cookieName,'small',7);
	}
}



///added by bob/mlr for group expansion
/* START
 * NEW CODE TO SHOW MEMBERS OF A GROUP
 */

function showLinkIfGroup (type, id, name, checkboxname, valueSuffix)
{
	if (typeof(valueSuffix) == "undefined") valueSuffix = "#h_Person";
	
	if (typeof(checkboxname) == "undefined" || checkboxname == null) {
		checkboxname = "h_getEntryNames";
	}
	var ALTTEXT_SHOWMEMBERS = QuickrLocaleUtil.getStringResource("FOLDER.SHOWMEMBERS");

	var retStr = "";
	if ( type == "h_ExternalGroup" )
	{		
		var srcid = escape(id).replace(/%/g,"_").replace(new RegExp("\/","g"),"__");
		
		retStr = "<a style=\"text-decoration:underline;font-weight:bold;\" title=\"" + ALTTEXT_SHOWMEMBERS + "\" id=\"" + srcid + "\" href=\"javascript: void expandMemberGroup(&quot;" + id + "&quot;,&quot;" + srcid + "&quot;,&quot;" + checkboxname + "&quot;,&quot;" + valueSuffix + "&quot;);\">" + name + "</a>";
	}
	else if ((type == "h_Person") || (type == "h_Group")  || (type == "h_Unknown"))
		retStr = name;
	return retStr;

};


/*******************************
* BB - Code goes through the 
* name and replaces commas with 
* slashes for the separatorsin 
* the canonical name.
*******************************/
function NormalizeCanonical(inStr)
{

	if (inStr.indexOf("=") == -1 || inStr.indexOf(",") == -1) return inStr;

	var bReplace = false;
	var outStr = "";
	
	
	/* loop through the string backwards and replace commas with slashes but only if before equals...*/
	for (var i = inStr.length - 1; i >= 0; i--) {
		var tmp = inStr.substring(i,i+1);

		if (tmp == "=") {
			bReplace = true;
		}
		else
		if (tmp == "/") {
			bReplace = false;
		}
		else
		if (tmp == "," && bReplace) {
			tmp = "/";
			if (outStr.substring(0,1) == " ") {  //remove any trailing spaces in between values
				outStr = outStr.substring(1);
			}			
			bReplace = false;
		}

		outStr = tmp + outStr;


	}

	return outStr;
	
	
}



function expandMemberGroup(unid, srcid, checkboxname, valueSuffix)
{
	if (typeof(valueSuffix) == "undefined") valueSuffix = "#h_Person";

	var ALTTEXT_SHOWMEMBERS = QuickrLocaleUtil.getStringResource("FOLDER.SHOWMEMBERS");
	var ALTTEXT_HIDEMEMBERS = QuickrLocaleUtil.getStringResource("FOLDER.HIDEMEMBERS"); 
	var srcid_new = "new_" + srcid;
	
	var el = document.getElementById(srcid);
	var el_new = document.getElementById(srcid_new);
	
	if (el_new) {
		el_new.parentNode.parentNode.removeChild(el_new.parentNode);
		el.setAttribute("title", ALTTEXT_SHOWMEMBERS);
		return;	
	}
	
	
	el.setAttribute("title", ALTTEXT_HIDEMEMBERS);
	
	while (el && el.tagName.toLowerCase() != "tr") {
		el = el.parentNode;
	}
	
	var el_tr = document.createElement("tr");
	el_tr.appendChild(document.createElement("td"));
	
	var el_td = document.createElement("td");
	el_td.setAttribute("colspan","7");
	el_td.setAttribute("id",srcid_new);
	el_tr.appendChild(el_td);
		
	el.parentNode.insertBefore(el_tr,el.nextSibling);
	
	
	dojo.require("dojo.widget.*");
	dojo.require("dojo.widget.TreeV3");
	dojo.require("dojo.widget.TreeNodeV3");
	dojo.require("dojo.widget.TreeBasicControllerV3");
	dojo.hostenv.writeIncludes();
	
	var htmltemplate = "<input type=\"checkbox\" value=\"{0}" + valueSuffix + "\" name=\"" + checkboxname + "\"/> {1}";

	showGroupMembership(unid, srcid_new, htmltemplate, false, false);
	


}


function showGroupMembership(groupName, rootDivName, htmltemplate, isExpanded, showTopLevel) {

	if (typeof(isExpanded) == "undefined") isExpanded = true;
	if (typeof(showTopLevel) == "undefined") showTopLevel = true;

	var root = document.getElementById(rootDivName);
	
	if (root && root.style.display == "none") {
		root.style.display = "block";
	}
	
	var placeName = window.location.href;
	

	placeName = placeName.substring(0, placeName.toLowerCase().indexOf(".nsf"));
	placeName = placeName.substring(0, placeName.lastIndexOf("/"));
	placeName = placeName.substring(placeName.lastIndexOf("/") + 1);

	var loc = "/dm/atom/library/@P{0}/action?action=ldapgetgroupmembers&query=[{1}]/";
	
	loc = loc.replace("{0}", placeName);
	loc = loc.replace("{1}", encodeURIComponent(groupName.replace(new RegExp("\/","g"), ",")));
	
	var subNodes = new Array();
	

	dojo.io.bind ({
		url: loc,
		method: "get",
		mimetype: "text/plain",
		load: function (type, data, evt) {
			var xmldata = _qp_getXMLDocFromString(data);

			var eroot = xmldata.getElementsByTagName('viewentries')[0];

			var entries = eroot.getElementsByTagName("entrydata");

			for (var i=0; i<entries.length; i++) {
				var xname = entries[i].getAttribute('name');
				xname = NormalizeCanonical(xname);
				var xval = _qp_getVersionColumnValue(entries[i]);
								
				var retStr = "";


				if (typeof (htmltemplate) != "undefined" && htmltemplate != null) {
					retStr = htmltemplate;
					retStr = retStr.replace("{0}",xname);
					retStr = retStr.replace("{1}",xval);
				}

				subNodes[subNodes.length] = {title: retStr};					

			}


			var controller = dojo.widget.createWidget("TreeBasicControllerV3");

			var treeNodes;
			
			if (showTopLevel) {
				treeNodes = [
					{
						title: groupName ,
						expandLevel: (isExpanded)?1:0,
						children: subNodes
					}
				]
			} else {
				treeNodes = subNodes;			
			}


			var tree = dojo.widget.createWidget("TreeV3", {listeners: [controller.widgetId]});

			tree.setChildren(treeNodes);

			root.appendChild(tree.domNode);	
			
			



		},
		
		error: function (err) {
			var controller = dojo.widget.createWidget("TreeBasicControllerV3");

			var treeNodes = [
				{
					title: groupName ,
					expandLevel: 1,
					children: subNodes
				}
			]


			var tree = dojo.widget.createWidget("TreeV3", {listeners: [controller.widgetId]});

			tree.setChildren(treeNodes);

			root.appendChild(tree.domNode);	
			
		},
		transport: "XMLHTTPTransport"
	});






}

function _qp_getXMLDocFromString(stext) {
	var doc;

	// code for IE
	if (window.ActiveXObject)
	{
		doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(stext);
	}
	// code for Mozilla, Firefox, Opera, etc.
	else
	{
		var parser=new DOMParser();
		doc=parser.parseFromString(stext,"text/xml");
	}

	return doc;
}

function _qp_getVersionColumnValue(node) {
	try {
		return node.childNodes[0].nodeValue;
	} catch (e) {
		return node.text;
	}
}
/* END
 * NEW CODE TO SHOW MEMBERS OF A GROUP
 */
/* ***************************************************************** */
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2008                                          */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/* ***************************************************************** */

// URL support utilities
URL = {}
URL.utils = {

	expParms : ["&ExpandView","&CollapseView","&Expand=","&Collapse="],
	EXPANDED : "0",
	COLLAPSED : "1",
	NEXPANDED : "2",
	NCOLLAPSED : "3",

	getExpandState: function() {
		// Set vars indicating whether folder contents are expanded or collapsed,
		// and at which document number, if any.
		// Return URL stripped expand/collapse param
		var bU=(typeof(h_FolderNavBaseURL)=="undefined" ? location.href : h_FolderNavBaseURL);
		var state=this.EXPANDED;
		var j = -1, docNo = -1;
		
		// Get which parm if any, and parm's length
		for (var i=0; i<this.expParms.length; i++) {
			if ((j=bU.indexOf(this.expParms[i])) != -1) {
				state=i;
				break;
			}
		}
		
		if ((state==this.NEXPANDED || state==this.NCOLLAPSED) && j>0) {
			// get doc# arg
			docNo=parseInt(bU.substring(j+this.expParms[state].length));
		}
		
		return {"state":state, "docNo":docNo};
	},

	makeExpandParm: function(state,docNo) {
		switch (state) {
		case this.NEXPANDED:
		case this.NCOLLAPSED:
		if (docNo >= 1)
			return this.expParms[state]+docNo;
			break;
		case this.COLLAPSED:
			return this.expParms[state];
			break;
		case this.NEXPANDED:
		default:
			return "";
		}
	},

	getViewUrl: function() {
		// actual view url w/o params
		var bU=(typeof(h_FolderNavBaseURL)=="undefined" ? location.href : h_FolderNavBaseURL);
		if ((i=bU.indexOf(".nsf")) > 0) {

			bU=bU.substring(0,i+4);
			var v="h_Index";

			if (typeof(h_FolderStorage) != "undefined")
				v=h_FolderStorage;
			else if (typeof(currentFolderStorage) != "undefined")
				v=currentFolderStorage;
			else if (typeof(defaultFolder) != "undefined")
				v=defaultFolder;
			else if (typeof(h_SystemName) != "undefined")
				v=h_SystemName;

			return bU+"/"+v;
		}
		return bU;
	},

	getProxyUrl: function() {
		// folder proxy doc url w/ ?OpenDocument
		var bU=(typeof(h_FolderNavBaseURL)=="undefined" ? location.href : h_FolderNavBaseURL);
		if ((i=bU.indexOf("?OpenDocument")) > 0) {
			return bU.substring(0,i+13);
		}
		return bU;
	},

	getNextStart: function() {
		// get Start value from "next page" URL
		var n=1;
		var i=-1;
		if (typeof(h_NextPageURL) != "undefined" && (i=h_NextPageURL.indexOf("&Start=")) > 0) {
			n=parseInt(h_NextPageURL.substring(i+7));
		}
		return n;
	},

	getSortParm: function() {
		// get Start value from "next page" URL
		var bU=(typeof(h_FolderNavBaseURL)=="undefined" ? location.href : h_FolderNavBaseURL);
		var i=-1;
		var col=-1;
		var ord=-1;
		if ((i=bU.indexOf("&ResortAscending=")) > 0) {
			col=parseInt(bU.substring(i+17));
			ord=0;
		}
		else if ((i=bU.indexOf("&ResortDescending=")) > 0) {
			col=parseInt(bU.substring(i+18));
			ord=1;
		}
		else {
			// no sort parm in URL
			return null;
		}
		return {"col":col,"ord":ord};
	},

	makeSortParm: function(col,ord) {
		if (col>=0 && ord>=0) {
			return "&Resort" + (ord==0 ? "A" : "De") + "scending=" + col;
		}
		else return "";
	}
}


// --------------------------------------------------------------------------------
//
// FOLDER MANAGEMENT
//
FM = {
	nonDocF: new Array("h_TaskList", "h_Members", "h_Calendar", "h_Tailor"),

	roomHasDocFolders: function() {
		for (var i=0; i < G_aToc.length; i++) {
			if (G_aToc[i].item.type=="1" && this.nonDocF.indexOf(G_aToc[i].item.SystemName) == -1) {
				return true;
			}
		}
		return false;
	}
}

FM.view = {

	// view object: "MM", etc.
	fvObj: "",
	cookie_IPP: "",
	cookie_Start: "",
	cookie_SortCol: "",
	cookie_SortOrd: "",
	cookie_ExpState: "",
	cookie_ExpDocNo: "",
	nextStart: "",
	docCount: "",
	aIppVals: [10,20,50,100,100000],

	makeURL: function(start,count,sortCol,sortOrd,expState,expDocNo,bUpdateView) {

		var szS = start || this.getStart(); 
		var szC = count || this.getIPP(); 
 		var sort = this.getSort();
 		var sCol = sortCol || (sort ? sort.col : -1);
 		var sOrd = sortOrd || (sort ? sort.ord : -1);
 		var expand = this.getExpand();
 		var eState = expState || (expand ? expand.state : URL.utils.EXPANDED);
 		var eDocNo = expDocNo || (expand ? expand.docNo : -1);

		if (typeof(Quickr81SupportUtil)=="undefined" || typeof(eval(FM.view.fvObj+".view.refresh"))=="undefined") {
			return (URL.utils.getProxyUrl() + "&Start="+szS + "&Count="+szC + URL.utils.makeSortParm(sCol,sOrd) + URL.utils.makeExpandParm(eState,eDocNo));
		} else {
			return (eval(this.fvObj+'.view.getBaseURL(bUpdateView)')
					  + "&Start="+szS + "&Count="+szC
					  + URL.utils.makeSortParm(sCol,sOrd)
					  + URL.utils.makeExpandParm(eState,eDocNo));
		}
	},

	init: function(fvO) {

		this.fvObj=fvO;
		this.nextStart=URL.utils.getNextStart();
		this.docCount=(typeof(h_FolderDocCount)=="undefined" ? 100000 : h_FolderDocCount);
		this.cookie_IPP="h_IPP_"+haikuName+"_"+h_PageUnid;
		this.cookie_Start="h_Start_"+haikuName+"_"+h_PageUnid;
		this.cookie_SortCol="h_SortCol_"+haikuName+"_"+h_PageUnid;
		this.cookie_SortOrd="h_SortOrd_"+haikuName+"_"+h_PageUnid;
		this.cookie_ExpState="h_ExpState_"+haikuName+"_"+h_PageUnid;
		this.cookie_ExpDocNo="h_ExpDocNo_"+haikuName+"_"+h_PageUnid;

		if (!this.isIPPSet()) {
			this.setIPP((typeof(h_FolderCount)=="undefined" ? 20 : h_FolderCount));
		}

		if (!this.isStartSet()) {
			this.setStart((typeof(h_FolderStart)=="undefined" ? 1 : h_FolderStart));
		}

		if (!this.isExpandSet()) {
			var exp=URL.utils.getExpandState();
			this.setExpand(exp.state,exp.docNo);
		}
		else if (fvO != "FV.summary") {
			this.refreshShowHideResponses();
		}

		if (this.getSort()==null) {
			var sort=URL.utils.getSortParm();
			if (sort) {
				this.setSort(sort.col,sort.ord);
			}
		}

		// Items-per-page buttons
		if (dojo.byId("itemsPerPage")) {
			this.refreshIpp();
		}

		// Paging (f|p|n|l) buttons:
  		if (dojo.byId("pgButtons")) {
			this.refreshPgBtns();
 		}

		if (typeof(dojo) !="undefined") {

			dojo.addOnLoad(function(){
				//init the locale stuff
				QuickrLocaleUtil.loadStringFiles("common", "/qphtml/skins/common", "QuickrCommonStrings");
			});
			

		}

	},

	toggleBtn: function(id,bShow,action) {
		var btnA=dojo.byId(id+"_a");
		var btnS=dojo.byId(id+"_s");
		if (bShow) {
			btnA.style.display="inline";
			btnS.style.display="none";
			if (typeof(action) != "undefined") {
				btnA.onclick=function(){eval(action);return false;};
			}
		}
		else {
			btnA.style.display="none";
			btnS.style.display="inline";
		}
	},

	refreshIpp: function(n) {
		// Refresh items-per-page buttons
		if (typeof(n) != "undefined") {
			this.setIPP(n);
		}

		for (var i=0; i<this.aIppVals.length; i++) {
			this.toggleBtn("ipp_"+this.aIppVals[i], (this.aIppVals[i] != this.getIPP()));
		}
	},

	refreshPgBtns: function(n) {
		// Refresh paging (f|p|n|l) buttons
		if (typeof(n) != "undefined") {
			this.setStart(n);
		}

		if (this.getStart()==1 || this.docCount==0) {
			this.toggleBtn("pgBtn_f",false);
			this.toggleBtn("pgBtn_p",false);
		}
		else {
			var prev=Math.max((this.getStart()-this.getIPP()), 1);
			this.toggleBtn("pgBtn_f",true,"javascript:FM.view.onPgBtn(1);");
			this.toggleBtn("pgBtn_p",true,"javascript:FM.view.onPgBtn("+prev+");");
		}

		var last=Math.max((this.docCount-this.getIPP()+1), 1);
		if (this.docCount==0 || this.getStart()>=last) {
			this.toggleBtn("pgBtn_n",false);
			this.toggleBtn("pgBtn_l",false);
		} else {
			this.toggleBtn("pgBtn_n",true,"javascript:FM.view.onPgBtn("+this.nextStart+");");
			this.toggleBtn("pgBtn_l",true,"javascript:FM.view.onPgBtn("+last+");");
		}
	},

	refreshABofC: function(a,c,nShowing) {
		// update "showing items a-b of c"
		var fsi=dojo.byId("FolderShowingItems");
		if (this.fvObj=="FV.tasks") {
			fsi.style.display="none";
		} else {
			if (fsi) {
				var b=Math.max(0, a+nShowing-1);
				var siA=dojo.byId("FolderShowingItems_a");
				var siB=dojo.byId("FolderShowingItems_b");
				var siC=dojo.byId("FolderShowingItems_c");
				if (siA && siB && siC) {
					siA.innerHTML=a;
					siB.innerHTML=b;
					siC.innerHTML=c;
				}
				fsi.style.visibility="visible";
			}
		}
	},

	refreshShowHideResponses: function() {
		// show/hide all responses link:
		var shr=dojo.byId("shr_div");
  		if (shr && getFolderStyle()=="5") {
			var a=dojo.byId("shr_a");
			var exp=this.getExpand();
			if (exp.state==URL.utils.COLLAPSED || exp.state==URL.utils.NCOLLAPSED) {
				a.innerHTML=QuickrLocaleUtil.getStringResource("FOLDER.SHOWALL");
				a.title=QuickrLocaleUtil.getStringResource("FOLDER.SHOWALL");
				a.onclick=function(){FM.view.onExpand(URL.utils.EXPANDED,"-1");return false;};
			} else {
				a.innerHTML=QuickrLocaleUtil.getStringResource("FOLDER.HIDEALL");
				a.title=QuickrLocaleUtil.getStringResource("FOLDER.HIDEALL");
				a.onclick=function(){FM.view.onExpand(URL.utils.COLLAPSED,"-1");return false;};
			}
			shr.style.display="block";
		}
	},

	onIpp: function(n) {

		if (typeof(Quickr81SupportUtil)=="undefined" || typeof(eval(FM.view.fvObj+".view.refresh"))=="undefined") {
			// view is not ajax-enabled; add params to url and reload the page:
			var url=this.makeURL(this.getStart(),n);
			this.setIPP(n);
			this.refreshPgBtns()
			location.href=url;
			return;
		}

		var now = new Date();
		var mType=eval(FM.view.fvObj+".view.mimeType");
		try {
			dojo.io.bind ({
				url: this.makeURL(this.getStart(),n) + '&timestamp=' + now.getTime(),
				method: "get",
				mimetype: (typeof(mType)=="undefined" ? "text/xml" : mType),
				load: function (type, data, evt) {eval(FM.view.fvObj+'.view.refresh(data)');FM.view.refreshIpp(n);FM.view.refreshPgBtns();},
				transport: "XMLHTTPTransport"
			});
			FM.view.showPgLoading(true);
		}
		catch(e) {
		}
	},

	onPgBtn: function(n) {

		if (typeof(Quickr81SupportUtil)=="undefined" || typeof(eval(FM.view.fvObj+".view.refresh"))=="undefined") {
			// view is not ajax-enabled; add params to url and reload the page:
			var url=this.makeURL(n,this.getIPP());
			this.refreshPgBtns(n);
			location.href=url;
			return;
		}

		var now = new Date();
		var mType=eval(FM.view.fvObj+".view.mimeType");
		try {
			dojo.io.bind ({
				url: this.makeURL(n,this.getIPP()) + '&timestamp=' + now.getTime(),
				method: "get",
				mimetype: (typeof(mType)=="undefined" ? "text/xml" : mType),
				load: function (type, data, evt) {eval(FM.view.fvObj+'.view.refresh(data)');FM.view.refreshPgBtns(n);},
				transport: "XMLHTTPTransport"
			});
			FM.view.showPgLoading(true);
		}
		catch(e) {
		}
	},

	onExpand: function(state,docNum) {

		var url=this.makeURL(this.getStart(),this.getIPP(),null,null,state,docNum);

		if (typeof(Quickr81SupportUtil)=="undefined" || typeof(eval(FM.view.fvObj+".view.refresh"))=="undefined") {
			// view is not ajax-enabled; add params to url and reload the page:
			this.setExpand(state,docNum);
			location.href=url;
			return;
		}

		var now = new Date();
		var mType=eval(FM.view.fvObj+".view.mimeType");
		try {
			dojo.io.bind ({
				url: url + '&timestamp=' + now.getTime(),
				method: "get",
				mimetype: (typeof(mType)=="undefined" ? "text/xml" : mType),
				load: function (type, data, evt) {FM.view.setExpand(state,docNum);eval(FM.view.fvObj+'.view.refresh(data)');FM.view.refreshPgBtns();},
				transport: "XMLHTTPTransport"
			});
			FM.view.showPgLoading(true);
		}
		catch(e) {
		}
	},

	onSortBtn: function(btn) {

		if (btn.id.indexOf("sortBtn_")==0) {
			var bAsc=(typeof(btn.className)=="undefined" || btn.className=="" ? true : !(btn.className.indexOf("Ascending")>0));
			var sCol=parseInt(btn.id.substring(8));
			var sOrd=(bAsc?"0":"1");
		}

		if (typeof(Quickr81SupportUtil)=="undefined" || typeof(eval(FM.view.fvObj+".view.refresh"))=="undefined") {
			// view is not ajax-enabled; add params to url and reload the page:
			var url=FM.view.makeURL(FM.view.getStart(),FM.view.getIPP(),sCol,sOrd);
			location.href=url;
			return;
		}

		var now = new Date();
		var mType=eval(FM.view.fvObj+".view.mimeType");
		try {
			dojo.io.bind ({
				url: FM.view.makeURL(1,FM.view.getIPP(),sCol,sOrd) + '&timestamp=' + now.getTime(),
				method: "get",
				mimetype: (typeof(mType)=="undefined" ? "text/xml" : mType),
				load: function (type, data, evt) {FM.view.setSort(sCol,sOrd);eval(FM.view.fvObj+'.view.refresh(data)');FM.view.refreshPgBtns(1);},
				transport: "XMLHTTPTransport"
			});
			FM.view.showPgLoading(true);
		}
		catch(e) {
		}
	},

	isIPPSet: function() {
		return (getCookie(this.cookie_IPP) != null);
	},

	setIPP: function(n) {
		if (n > 0) {
			setCookie(this.cookie_IPP, n, 7);
		}
	},

	getIPP: function() {
		var n=getCookie(this.cookie_IPP);
		return (n ? n : 20);
	},

	isStartSet: function() {
		return (getCookie(this.cookie_Start) != null);
	},

	setStart: function(n) {
		if (n > 0) {
			setCookie(this.cookie_Start, n, 7);
		}
	},

	getStart: function() {
		var n=getCookie(this.cookie_Start);
		return (n ? n : 1);
	},

	isExpandSet: function() {
		return (getCookie(this.cookie_ExpState) != null && getCookie(this.cookie_ExpDocNo) != null);
	},

	setExpand: function(state,docNo) {
		setCookie(this.cookie_ExpState, state, 7);
		setCookie(this.cookie_ExpDocNo, docNo, 7);
		this.refreshShowHideResponses();
	},

	getExpand: function() {
		var state=getCookie(this.cookie_ExpState);
		var docNo=getCookie(this.cookie_ExpDocNo);
		return (state && docNo ? {"state":state, "docNo":docNo} : {"state":URL.utils.EXPANDED, "docNo":-1});
	},

	setSort: function(col,ord) {
		if (col>=0 && ord>=0) {
			setCookie(this.cookie_SortCol, col, 7);
			setCookie(this.cookie_SortOrd, ord, 7);
		}
	},

	getSort: function() {
		var col=getCookie(this.cookie_SortCol);
		var ord=getCookie(this.cookie_SortOrd);
		if (col && ord) {
			return {"col":col, "ord":ord};
		} else {
			return null;
		}
	},

	reqData: function(bUpdView) {

		if (typeof(Quickr81SupportUtil)=="undefined" || typeof(eval(FM.view.fvObj+".view.refresh"))=="undefined") {
			// view is not ajax-enabled; add params to url and reload the page:
			var url=this.makeURL(this.getStart(),this.getIPP(),null,null,null,null,bUpdView);
			location.href=url;
			return;
		}

		var now = new Date();
		var mType=eval(FM.view.fvObj+".view.mimeType");
		try {
			dojo.io.bind ({
				url: this.makeURL(this.getStart(),this.getIPP(),null,null,null,null,bUpdView) + '&timestamp=' + now.getTime(),
				method: "get",
				mimetype: (typeof(mType)=="undefined" ? "text/xml" : mType),
				load: function (type, data, evt) {eval(FM.view.fvObj+'.view.refresh(data)');FM.view.refreshPgBtns();},
				transport: "XMLHTTPTransport"
			});
			FM.view.showPgLoading(true);
		}
		catch(e) {
		}
	},

	showPgLoading: function(bLoading,msg) {
		var pc=dojo.byId("pageContent");
		var pcl=dojo.byId("PageContentLoading");
		if (pc && pcl) {
			if (bLoading) {
				pcl.style.display="block";
				pc.style.display="none";
				FM.view.setPgLoadingMsg(msg);
			} else {
				pcl.style.display="none";
				pc.style.display="block";
			}
		}
	},

	setPgLoadingMsg: function(msg) {
		// FIX ME: translate
		var lMsg=msg || "Téléchargement en cours...";
		var plm=dojo.byId("PageContentLoadingMsg");
		if (plm) {
			plm.innerHTML=lMsg;
		}
	},

	initListDetailsBtns: function() {
		var btnS=dojo.byId("summaryBtn");
		var btnD=dojo.byId("detailsBtn");
		if (btnS && btnD) {
			if (h_SetReadScene == 'h_AbstractsFolderRead') { 
				/* We're in Summary view */
				btnD.className="lotusSprite lotusView lotusListOff";
				btnS.className="lotusSprite lotusView lotusDetailsOn";
				dojo.event.connect(btnS, "onclick", function(e) {FM.view.reqData();});
				btnS.href="#";
				btnD.href=this.changeViewURL(true);
			}
			else {
				/* We're in Details view */
				btnD.className="lotusSprite lotusView lotusListOn";
				btnS.className="lotusSprite lotusView lotusDetailsOff";
				dojo.event.connect(btnD, "onclick", function(e) {FM.view.reqData();});
				btnD.href="#";
				btnS.href=this.changeViewURL(false);
			}
		}
		dojo.byId("showListDetails").style.display="block";
	},

	changeViewURL: function(bList) {
		return '../../h_Toc/'+h_FolderDoc.h_Unid+'/?OpenDocument&Start='+FM.view.getStart()
		+ '&Count='+(bList ? 20 : 10)
		+ '&PresetFields=h_SetReadScene;'
		+ (bList ? 'h_StdFolderRead' : 'h_AbstractsFolderRead');
	},
	
	attachmentIconName: function(name) {
		var returnVal = "default";
		
		if (typeof(name) != "undefined" && name != null) {
			if (name.indexOf(".") > -1) {
				var suffix = name.substring(name.lastIndexOf(".")+1).toLowerCase();
				
				switch (suffix) {

					case "doc":
					case "odt":
					case "sxw":
					case "lwp":
					case "dot":
					case "ott":
					case "stw":
					case "mwp":
						returnVal = "wordprocessing";
						break;
					
					case "xls":
					case "ods":
					case "sxc":
					case "123":
					case "csv":
					case "xlt":
					case "ots":
					case "stc":
					case "12m":
						returnVal = "data";
						break;
					
					case "ppt":
					case "prz":
					case "odp":
					case "sxi":
					case "prz":
					case "pot":
					case "otp":
					case "mas":
					case "smc":
					case "sti":
						returnVal = "presentation";
						break;
						
					case "pdf":
						returnVal = "pdf";
						break;
						
					case "txt":
					case "rtf":
					case "log":
					case "csv":
						returnVal = "text";
						break;
						
					case "wav":
					case "mp3":
					case "wma":
						returnVal = "audio";
						break
						
					case "wmv":
					case "mpg":
					case "avi":
					case "mpeg":
					case "mp4":
						returnVal = "video";
						break;
						
					case "zip":
					case "gzip":
					case "rar":
					case "gz":
					case "tar":
					case "arc":
						returnVal = "compressed";
						break;
						
					case "gif":
					case "jpg":
					case "jpeg":
					case "bmp":
					case "png":
						returnVal = "image";
						break;

				
				}
			
			}	
		
		}
		return returnVal;
	},

	getIconImg: function( type, form, attName, bShowLargeIcon ) {
	
		if (typeof(bShowLargeIcon) == "undefined") bShowLargeIcon = false;
		
		var img=document.createElement("img");
		img.setAttribute("border","0");
		img.setAttribute("align","middle");
		img.setAttribute("valign","middle");
		
		var newSrc = GetDocTypeIconImgSrc(type,form,"",((bShowLargeIcon)?"LG":"SM"));
		
		
		//these types might need a different icon
		var aCustomTypes = [ "docupload", "docword", "docexcel", "docppoint", "docplain" ];
		
		var newSrcName = newSrc.substring(newSrc.lastIndexOf("/")+1);
		
		var bCustomType = false;

		for (var i = 0; i < aCustomTypes.length; i++) {
			if (newSrcName.indexOf(aCustomTypes[i]) == 0) {
				bCustomType = true;
				break;
			}
		}
		

		if (bCustomType) {
		
			if (attName != "") {

				var aFiles = new Array();		

				//first, let's get the uploaded attachments, not the conversions...
				var aN = attName.split(',');  
				for (var i = 0; i < aN.length; i++) {
					if (aN[i].search(/^TMP[0-9]{2}.*\.[gjch]/i) < 0) {
						aFiles[aFiles.length] = aN[i];
					}
				}

				//now let's loop through the uploaded files and inspect the types...
				var suffix = null;


				for (var i = 0; i < aFiles.length; i++) {
					var tmpSuffix = "";
					if (aFiles[i].lastIndexOf(".") > -1) {
						tmpSuffix = aFiles[i].substring(aFiles[i].lastIndexOf(".")+1).toLowerCase();
					}

					if (suffix == null && tmpSuffix.length > 0) {
						suffix = tmpSuffix;
					} else if (suffix != tmpSuffix) {  //there is more than one file with a different extension...
						suffix = null;
						break;
					}
				}

				if (suffix != null) {
					var imgType = this.attachmentIconName("test." + suffix) + "_" + ((bShowLargeIcon)?"80":"16") + ".gif";
					if (imgType.indexOf("default") != 0) {
						newSrc="/qphtml/skins/quickrentry/images/"+imgType;
					}

				}
				
			}
				
				
			
		}
		
		img.src = newSrc;
		
		return img;
	},

	reload: function() {
		if (typeof(Quickr81SupportUtil) != "undefined") {
			// use Ajax to refresh content
			FM.view.reqData();
		}
		else {
			location.reload();
		}
	},

	rmUnids: null,
	rmNames: null,

	removeChecked: function() {
		this.rmUnids=FM.check.getSelections(theForm.h_SelectedEntry);
		if (this.rmUnids.length>0 && confirm(QuickrLocaleUtil.getStringResource("FOLDER.RESPONSES"))) {
			this.rmNames=FM.check.getSelectionTitles(theForm.h_SelectedEntry);
			FM.view.showPgLoading(true,QuickrLocaleUtil.getStringResource("FOLDER.DELETINGMANY"));
			this.rmOneChecked();
		}
		else {
			alert(QuickrLocaleUtil.getStringResource("FOLDER.REMOVE"));
		}
	},

	rmOneChecked: function() {
		if (FM.view.rmUnids.length>0) {
			var dUnid=FM.view.rmUnids[FM.view.rmUnids.length-1];
			var dName=FM.view.rmNames[FM.view.rmNames.length-1];

			FM.view.setPgLoadingMsg(QuickrLocaleUtil.getStringResource("FOLDER.DELETING").replace("{0}",dName));

			FM.view.rmUnids.length--;
			if (FM.view.rmNames.length>0) {
				FM.view.rmNames.length--;
			}

			DM.service.submit((typeof(h_FolderUNID)=="undefined" ? "" : h_FolderUNID),
									dUnid,"deleteDocument",null,
									FM.view.rmOneChecked,FM.view.rmOneChecked);
		}
		else {
			// we are done
			FM.view.reload();
		}
	},

	emptyMsg: function() {
		if (h_FolderStorage=="h_Index") {
			return QuickrLocaleUtil.getStringResource("FOLDER.EMPTYINDEX");
		} else {
			return QuickrLocaleUtil.getStringResource("FOLDER.EMPTYFOLDER")
			+ (currentUserAccess > 2 ? " "+QuickrLocaleUtil.getStringResource("FOLDER.YOUCANCREATE") : "");
		}
	}

} // FM.view



//
// CHECKBOX SUPPORT
//
FM.check = {

	selectAll: function(el) {
		var bC = el.checked;

		if (typeof(theForm.h_SelectedEntry) != "undefined") { 
			if (!isNaN (theForm.h_SelectedEntry.length)) {		
				for (var i = 0; i < theForm.h_SelectedEntry.length; i++) {
					theForm.h_SelectedEntry[i].checked = bC;
				}
			} 
			else {
				theForm.h_SelectedEntry.checked = bC;
			}
		}
	},

	select: function(el) {
		// Uncheck the "select all" box if checked
		if (currentUserAccess >= 6) {
			theForm.allDocsSelected.checked = false;
		}
	},

	getSelections: function(inp) { 
		var aCB = new Array( );
		if (typeof(inp) != "undefined") {
			  
			if (!isNaN(inp.length)) {
				for (var i = 0; i < inp.length; i++) {
					if (inp[i].checked == true) {
						aCB[aCB.length] = inp[i].value;
					}
				}
			}
			else if (inp.checked == true) {
				aCB[aCB.length] = inp.value;
			}
		}
		return aCB;
	},

	getSelectionTitles: function(inp) { 
		var aCB = new Array( );
		if (typeof(inp) != "undefined") {
			  
			if (!isNaN(inp.length)) {
				for (var i = 0; i < inp.length; i++) {
					if (inp[i].checked == true) {
						aCB[aCB.length] = inp[i].title;
					}
				}
			}
			else if (inp.checked == true) {
				aCB[aCB.length] = inp.title;
			}
		}
		return aCB;
	},

	enable: function(inp,yn) { 
		if (typeof(inp) != "undefined") {
			if (!isNaN(inp.length)) {
				for (var i = 0; i < inp.length; i++) {
					inp[i].disabled=(!yn);
				}
			}
			else {
				inp.disabled=(!yn);
			}
		}
	},

	checkByValue: function(inp,v) { 
		if (typeof(inp) != "undefined") {
			if (!isNaN(inp.length)) {
				for (var i = 0; i < inp.length; i++) {
					inp[i].checked=(inp[i].value==v);
				}
			}
			else {
				inp.checked=(inp.value==v);
			}
		}
	},

	makeInput: function(name) {
		var ch;
		if (document.all) {
			// IE: name dropped unless created like this!
			ch=document.createElement("<input name='"+name+"'/>");
		}
		else {
			ch=document.createElement("input");
			ch.setAttribute("name",name);
		}
		return ch;
	},

	makeDisabled: function() {
		var ch=FM.check.makeInput("h_Disabled");
		ch.setAttribute("type","checkbox");
		ch.setAttribute("disabled",true); // ???
		return ch;
	},
	
	makeSelect: function(type,name,unid) {
		var ch;
		if (currentUserAccess<6 || type=="1") {
			// no checkbox if not manager or if folder
			ch=FM.check.makeDisabled();
		}
		else {
			ch=FM.check.makeInput("h_SelectedEntry");
			ch.setAttribute("type","checkbox");
			ch.setAttribute("value",unid);
			ch.setAttribute("title",name);
		}
		return ch;
	},

	makeSelectAll: function(t) {
		var ch;
		if (currentUserAccess<6) {
			ch=FM.check.makeDisabled();
		}
		else {
			ch=FM.check.makeInput("allDocsSelected");
			ch.setAttribute("type","checkbox");
			ch.id="allDocsSelected";
			ch.setAttribute("title",t);
		}
		return ch;
	}

} // FM.check


// =====================================================


FV = {}


FV.responses = {

	aChOnLev : new Array(0,0),	  // # of Doc children on level [i]

	// Indent & Expand image tags
	indImgTag : '<img style="width:18px;height:18px;vertical-align:middle;" src="/qphtml/html/common/treenode_%s.gif"/>',
	indImgTagBg : '<img style="width:18px;height:18px;vertical-align:middle;'
		+ 'background-image:url(/qphtml/html/common/treenode_grid_%g.gif);'
		+ '" src="/qphtml/html/common/treenode_%s.gif"/>',
	twImgTag : '<img style="width:18px;height:18px;vertical-align:middle;'
		+ 'background-image:url(/qphtml/html/common/treenode_grid_%g.gif);'
		+ '" src="/qphtml/html/common/treenode_expand_%s.gif"'
		+ ' onclick="javascript:FV.responses.doTheTwist(\'%n\',%b);"/>',
	rspImgTag :'<img src="/qphtml/html/common/response%a.gif" style="padding-right:0.5em;vertical-align:middle;"/>',

	rspImg: function(bAtt) {
		return (bAtt ? this.rspImgTag.replace(/%a/,'-attach') : this.rspImgTag.replace(/%a/,''));
	},

	indImg: function(src, bg) {
		return (bg ? this.indImgTagBg.replace(/%s/,src).replace(/%g/,bg) : this.indImgTag.replace(/%s/,src));
	},

	twImg: function(bExp, bg, num) {
		var pm = (bExp?'plus':'minus');
		return this.twImgTag.replace(/%s/,pm).replace(/%n/,num).replace(/%b/,bExp).replace(/%g/,bg);
	},

	doTheTwist: function(docNum, bExpand) {
		FM.view.onExpand((bExpand ? URL.utils.NEXPANDED : URL.utils.NCOLLAPSED), docNum);
	},

	makeIndent: function(lev,docNo,nC,bAtt) { 
		var html = "";
		var rImg = (lev>1 ? this.rspImg(bAtt) : "");
		
		// record #children at this level
		this.aChOnLev[lev] = nC;
		
		if (lev > 1) {
			// One child down
			this.aChOnLev[lev-1]--;
			
			// write preceeding blanks
			html += this.indImg('blank');
			for (var i=2; i < lev; i++) {
					if (this.aChOnLev[i-1] > 0)
						html += this.indImg('blank', 'v');
					else
						html += this.indImg('blank');
			}
		}
		
		if (nC > 0) {
			// doc has child(ren)
			
			// Select "+" or "-" for twisty
			var bExp = false;
			var expand=FM.view.getExpand();
			switch (expand.state)
			{
			case URL.utils.NEXPANDED:
				if (docNo != expand.docNo &&
					 docNo != expand.docNo.substr(0,docNo.length))
					bExp = true;
				break;
			case URL.utils.NCOLLAPSED:
				if (docNo == expand.docNo ||
					 docNo != expand.docNo.substr(0,docNo.length))
					bExp = true;
				break;
			case URL.utils.COLLAPSED:
				bExp = true;
				break;
			default:
				;
			}
			
			if (lev > 1)
				html += this.twImg(bExp, (this.aChOnLev[lev-1]>0 ? 't' : 'l'), docNo);
			else
				html += this.twImg(bExp, 'x', docNo);
		}
		else if (lev > 1) {
			// no children
			html += this.indImg('blank', (this.aChOnLev[lev-1]>0 ? 't' : 'l'));
		}
		
		html += rImg;
		return html;
	},

	SimpleResponseIndent: function(lev, nC, bAtt) { 
		var html = "";
		var rImg = "";
		
		// record #children at this level
		this.aChOnLev[lev] = nC;
		
		if (lev > 1) {
			// One child down
			this.aChOnLev[lev-1]--;
			
			// write preceeding blanks
			html += this.indImg('blank');
			for (var i=2; i < lev; i++) {
				if (this.aChOnLev[i-1] > 0)
					html += this.indImg('blank', 'v');
				else
					html += this.indImg('blank');
			}
			rImg=this.rspImg(bAtt);
		}
		
		html += this.indImg('blank', (this.aChOnLev[lev-1]>0 ? 't' : 'l'));
		
		html += rImg;
		return html;
	}
}


// ------------------------------------------------------------

FV.list = {

	init: function() {
		FV.list.view.init();
		dojo.byId("pageNavBar").style.display="block";
	}
}

FV.list.view = {

	baseURL: URL.utils.getProxyUrl() + "&Form=h_FolderViewJSON",
   mimeType: "text/javascript",
	// Use these when convert to use ReadViewEntries:
//   	baseURL: URL.utils.getViewUrl() + "?ReadViewEntries&PreFormat&OutputFormat=JSON",
//   	mimeType: "application/x-javascript",
	aColVal: new Array(),

	init: function() {
		FM.view.init("FV.list");
	},

	getBaseURL: function(bUpdView) {
		// update view (variables)?
		return this.baseURL + "&PreSetFields=h_UpdateView;"+(typeof(bUpdView)=="undefined" || bUpdView ? "1" : "0");;
	},

	resetColVal: function() {
		this.aColVal.length=0;
	},

	setColVal: function(col,val) {
		
		if((col=="h_Created")||(col=="h_DisplayModified")){
		if(isHijri||isHebrew){
			val = convertDateString(val);
		}}
		
		
		if (col != "") {
			this.aColVal[this.aColVal.length] = {'col': col, 'val' : val};
		}
	},

	refresh: function(data) {
		// Reset vars
		iTotNumOfDocs = 0;
		iDocArrayCount = 0;

		try
		{
			var items=data.items;

			// current view
			var fvt1=dojo.byId("dragTable");
			// new view
			var fvt2=document.createElement("table");
			fvt2.setAttribute("border","0");
			fvt2.setAttribute("cellPadding","0"); 
			fvt2.setAttribute("cellSpacing","0"); 
			fvt2.className="FolderTable"; 
			fvt2.setAttribute("width","100%");
				
			if (items.length > 0) {
			
				 // append title bar
				 folderView_appendTitleBar(fvt2);

				// append view entries
				var fvn=item=null;
				for (var i=0; i<items.length; i++)
				{
					var item=items[i].item;
					
					UpdateDocArray( iDocArrayCount++, item.Unid, item.HasParent, item.HasChildren);

					iTotNumOfDocs++;
					
					// get optional column values
					this.resetColVal();
					var colVals=item.other_columns;
					for (var j = 0; j < (colVals.length-1); j++) {
						this.setColVal(colVals[j].name, colVals[j].value);
					}
					
					fvn=FV.list.view.makeItem(
						item.Type, item.Name.replace(/\\&quot;/g,"&quot;"), item.Unid,
						GenerateQPObjURLAnchorTag(data.FolderStorage, item.Unid, item.URLpointer, item.URLNewWindow, item.Type),
						item.Form, item.HasParent, item.HasChildren, item.DocLevel, item.RevNum, item.DocNumber,
						item.Attachments,
						item.AttachLengths,
						item.IsLocked,
						item.Author,
						item.AuthorDN,
						item.LastEditorDN,
						item.Descendants
					);
					fvt2.appendChild(fvn);
				}

				// record last doc #
				FM.view.nextStart=item.DocNumber;
			}
			else {
				// empty folder
				FM.view.nextStart=0;
				if (qp_getElementsByClassName("h-folderEmpty", "div", fvt1.parentNode).length==0) {
					var div=document.createElement("div");
					div.className="h-folderEmpty";
					div.innerHTML=FM.view.emptyMsg();
					fvt1.parentNode.appendChild(div);
				}
			}

			// update "showing items a-b of c"
			FM.view.refreshABofC(data.FolderAbsStart,data.FolderDocCount,iTotNumOfDocs);
			
			// replace view
			fvt1.parentNode.replaceChild(fvt2,fvt1);
			fvt2.id="dragTable";
			
			if (items.length > 0) {
				// run the context menu/person card/DND stuff
				QP_ContextMenu_attachMenus(fvt2);
				QP_DragAndDrop_createObjects("tbody", "dragTable");
			}
			
			// show new view
			FM.view.showPgLoading(false);
			
			if (items.length > 0 && G_ProfileServer != "") {
				// get Javlin cards
				QP_PersonMenu.prototype = new QP_ContextMenu;
				QP_PersonMenu = QP_PersonMenu_javlin;
				qp_setJavelinNames(fvt2);
			}
		}
		catch (e)
		{
		}
	},

	makeItem: function(type,name,unid,aName,form,hasP,nC,lev,revNum,docNum,attName,attSize,isLocked,auth,aDN,eDN,nDD) {

		var tr=document.createElement("tr");
		tr.className="h-folderItem-bg";

		// Checkbox
		var td0=document.createElement("td");
		td0.className="h-folderItem-text";
		td0.setAttribute("width","10");
		var ch=FM.check.makeSelect(type,name,unid);
		td0.appendChild(ch);
		ch.onclick=function(){FM.check.select(this);}
		ch.onmouseover=function(){this.style.cursor='default';}
		tr.appendChild(td0);

		// Checked-out icon
		var td1=document.createElement("td");
		td1.className="h-folderItem-text";
		td1.style.textAlign="center";
		var img=document.createElement("img");
		if (isLocked=="1") {
			img.src="/qphtml/html/common/check_out_you.gif";
			img.alt=img.title=auth;
		}
		else {
			img.src="/qphtml/html/common/transparent.gif";
		}
		td1.appendChild(img);
		tr.appendChild(td1);

		// Doc icon
		var td2=document.createElement("td");
		td2.className="h-folderItem-text";
		td2.style.textAlign="center";
		if (lev=="1") {
			td2.appendChild(FM.view.getIconImg(type,form,attName));
		}
		tr.appendChild(td2);

		// Drag handle, response indent(s), title, rev#
		var td3=document.createElement("td");
		td3.className="h-folderItem-text";
		var span=document.createElement("span");
		if (lev=="1" && type != "1") {
			span.className="h-dragSource";
			span.id="dragSrc_"+unid;
			span.innerHTML=QP_DragAndDrop_makeHandle(unid);
		}
//		span.innerHTML += GenerateResponseIndent(lev,docNum,nC,(attName!=''))
		span.innerHTML += FV.responses.makeIndent(lev,docNum,nC,(attName!=''))
		+ (typeof(aName) != "undefined" ? GenerateQPObjURLAnchor(type,aName,name) : name);
		td3.appendChild(span);
		if (revNum && revNum != "") {
			 // removed for 8.1
			 //td3.appendChild(document.createTextNode("&nbsp;"+GenerateRevisionText(revNum)));
		}
		tr.appendChild(td3);

		// Other (optional/custom) columns:
		for (var i=0; i<this.aColVal.length; i++) {
			var td=document.createElement("td");
			td.className="h-folderItem-text";

			switch (this.aColVal[i].col) {
			case "h_Author":
				td.innerHTML=GetMemberProfileName(aDN,this.aColVal[i].val);
				td.style.whiteSpace="normal";
				break;
			case "h_LastEditorDisplayName":
				td.innerHTML=GetMemberProfileName((eDN==""?aDN:eDN),this.aColVal[i].val);
				td.style.whiteSpace="normal";
				break;
			case "h_DisplayModified":
			case "h_Created":
				// disabled anchor w/ timestamp when hover
				var ts=this.aColVal[i].val;
				iSpc=ts.indexOf(' ');
				var a=document.createElement("a");
				a.innerHTML=(iSpc>=0 ? ts.substring(0,iSpc) : ts);
				a.title=a.alt=ts;
				a.style.textDecoration="none";
				td.appendChild(a);
				break;
			case "h_AttachmentNames":
				if (typeof(attName) != "undefined" && attName != "") {
					// Special case for attachments
					td.className="h-folderItem-text download";
					td.innerHTML=GenerateAttachmentsAnchor(unid,attName,attSize,form);
				}
				break;
			default:
				td.innerHTML=this.aColVal[i].val;
				break;
			}
			tr.appendChild(td);
		}

		// tbody needed for IE!
 		var tbody=document.createElement("tbody");

		// Make the tbody a drag container if:
 		// - not a folder or response
		// - user not a Reader
		// - not a top doc with responses unless manager
		if (UIDragAndDropIsEnabled()
			 && type != "1"
			 && lev==1
			 && currentUserAccess>2
			 && (nC==0 || currentUserAccess>=6))
		{
			tbody.id="DC_"+unid;
			tbody.onmouseover=function(){this.className="h-dragSource-selected"; dojo.byId("DH_"+unid).style.visibility="visible";};
			tbody.onmouseout=function(){this.className="h-dragSource-deselected"; dojo.byId("DH_"+unid).style.visibility="hidden";};
		}

 		tbody.appendChild(tr);
		return tbody;
	},

	makeTitleBar: function(aCols,saTitle) {
		var tr=document.createElement("tr");
		tr.className="lotusSort";
		tr.id="viewTitleBar";

		// checkbox col
		var td0=document.createElement("td");
		td0.className="h-folderItem-text";
		td0.setAttribute("width","0");
		var ch=FM.check.makeSelectAll(saTitle);
		td0.appendChild(ch);
		ch.onclick=function(){FM.check.selectAll(this);}
		tr.appendChild(td0);

		// checked-out icon col
		var th0=document.createElement("th");
		th0.setAttribute("vAlign","middle");
		th0.setAttribute("width","16");
		th0.style.textAlign="center";
		var img=document.createElement("img");
		img.src="/qphtml/html/common/transparent.gif";
		th0.appendChild(img);
		tr.appendChild(th0);

		var a;
		var th;
		var col;
		var sort=FM.view.getSort();
		for (var i=0; i<aCols.length; i++) {

			col=aCols[i];

			th=document.createElement("th");
			th.setAttribute("nowrap","");
			th.setAttribute("vAlign","middle");
			th.setAttribute("width",col.width);
			th.style.overflow = 'hidden';
			th.style.verticalAlign = 'middle';
			th.style.padding="3px 0px";
			th.style.textAlign=col.align;

			a=document.createElement("a");
			a.innerHTML=col.name;
			a.href="#";
			if (col.sort > -2) {
				// sortable col
				var atitle=QuickrLocaleUtil.getStringResource("FOLDER.SORTCOL");
				atitle = atitle.replace("{0}", col.name);
				a.title = atitle;
				a.id="sortBtn_"+col.pos;

				if (typeof(Quickr81SupportUtil) != "undefined") {
					// new style 2-way Ajax sort with cookies
					a.onclick=function(){FM.view.onSortBtn(this);return false;};

					if (sort) {
						if (col.pos==sort.col) {
							a.className="lotusActiveSort lotus" + (sort.ord=="0" ? "A" : "De") + "scending";
						}
					}
					else if (col.sort >= 0) {
						a.className="lotusActiveSort lotus" + (col.sort=="0" ? "A" : "De") + "scending";
						FM.view.setSort(col.pos,col.sort);
					}
				}
				else {
					// old style 3-way sort
					var html=MakeTitle(col.name,col.pos);
					var bIsSorted=(html.indexOf("Sorted")>0);
					var i1=html.indexOf("href=");
					if (i1>0) {
						var html2=html.substring(i1+5);
						var i2=html2.indexOf(" ");
						var url=html2.substring(0,i2);
						if (bIsSorted) {
							a.className="lotusActiveSort lotus" + ((url.indexOf("Descending")>0) ? "A" : "De") + "scending";
						}
						a.href=url;
					}
				}
			}
			else {
				// not sortable
				a.style.cursor="default";
				a.style.textDecoration="none";
			}

			th.appendChild(a);
			tr.appendChild(th);
		} 

		// Needed for IE!
		var tbody=document.createElement("tbody");
		tbody.appendChild(tr);
		return tbody;
	}

} // FV.list.view


// ------------------------------------------------------------

FV.summary = {

	init: function() {
		FV.summary.view.init();
		dojo.byId("pageNavBar").style.display="block";
	}
}

FV.summary.view = {

	baseURL: URL.utils.getProxyUrl() + "&PresetFields=h_SetReadScene;h_AbstractsFolderRead",

	getBaseURL: function() {
		 return this.baseURL;
	},

	init: function() {
		FM.view.init("FV.summary");
		// force IPP and Start to be defaults or whatever's in URL,
		// because preset cookie values don't affect non-AJAX views
		FM.view.setIPP((typeof(h_FolderCount)=="undefined" ? 10 : h_FolderCount));
		FM.view.setStart((typeof(h_FolderStart)=="undefined" ? 1 : h_FolderStart));
		FM.view.refreshIpp();
		FM.view.refreshPgBtns();
	}
}


// ------------------------------------------------------------

FV.tasks = {

	init: function() {
		FV.tasks.view.init();
		dojo.byId("pageNavBar").style.display="block";
		var pnbt=dojo.byId("pageNavBarTop");
		var thdr=dojo.byId("h_taskHeader1");
		if (pnbt && thdr) {
			// move tasks nav to top nav bar
			var thdr2=thdr.cloneNode(true);
			var pnbt2=document.createElement("div");
			pnbt2.className="lotusPaging";
			pnbt2.appendChild(thdr2);
			pnbt.parentNode.replaceChild(pnbt2,pnbt);
			pnbt2.id="pageNavBarTop";
			thdr.parentNode.removeChild(thdr);

		}
	}
}

FV.tasks.view = {

	baseURL: URL.utils.getProxyUrl(),

	getBaseURL: function() {
		 return this.baseURL;
	},

	init: function() {
		FM.view.init("FV.tasks");
		// force IPP and Start to be defaults or whatever's in URL,
		// because preset cookie values don't affect non-AJAX views
		FM.view.setIPP((typeof(h_FolderCount)=="undefined" ? 20 : h_FolderCount));
		FM.view.setStart((typeof(h_FolderStart)=="undefined" ? 1 : h_FolderStart));
		FM.view.refreshIpp();
		FM.view.refreshPgBtns();
	}
}


// ------------------------------------------------------------

FV.calendar = {

	init: function() {
		FV.calendar.view.init();
		dojo.byId("pageNavBar").style.display="block";
		var pnbt=dojo.byId("pageNavBarTop");
 		var chdr=dojo.byId("h_calendarHeader");
		if (pnbt && chdr) {
			// move calendar nav to top nav bar
			var chdr2=chdr.cloneNode(true);
			var pnbt2=document.createElement("div");
			pnbt2.className="lotusPaging";
			pnbt2.appendChild(chdr2);
			pnbt.parentNode.replaceChild(pnbt2,pnbt);
			pnbt2.id="pageNavBarTop";
			chdr.parentNode.removeChild(chdr);

		}
 	}
}

FV.calendar.view = {

	baseURL: URL.utils.getProxyUrl(),

	getBaseURL: function() {
		 return this.baseURL;
	},

	gridBtns: ["","calSelectTwoDays","calSelectOneWeek","calSelectTwoWeeks","calSelectOneMonth"],
	gridImgs: ["","cal2day-sel.gif","calweek-sel.gif","cal2week-sel.gif","calmonth-sel.gif"],

	init: function() {
		FM.view.init("FV.calendar");
		// force IPP and Start to be defaults or whatever's in URL,
		// because preset cookie values don't affect non-AJAX views
		FM.view.setIPP((typeof(h_FolderCount)=="undefined" ? 20 : h_FolderCount));
		FM.view.setStart((typeof(h_FolderStart)=="undefined" ? 1 : h_FolderStart));

		// select cal view icon
		var i=location.href.indexOf("&Grid=");
		var g=3;
		if (i>0) {
			g=parseInt(location.href.substring(i+6));
		}
		if (g>0 && g<this.gridBtns.length) {
			var btn=dojo.byId(this.gridBtns[g]);
			if (btn) {
				btn.src="/qphtml/attachments/"+this.gridImgs[g];
			}
		}
	}
}
/* ***************************************************************** */
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2007, 2008                                    */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/* ***************************************************************** */

/* 5724-S31                                                          */
/* disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */
/*                                                                   */
/*********************************************************************/


// QUICKR DOMINO DOC MANAGEMENT

DM = {
	init: function() {
		if (typeof(dojo) !="undefined") {
			dojo.addOnLoad(function(){
				//init the locale stuff
				QuickrLocaleUtil.loadStringFiles("common", "/qphtml/skins/common", "QuickrCommonStrings");
			});
		}
	},

	roomNsf: function() {
		return (typeof(currentRoom) != "undefined" && currentRoom && currentRoom.roomNsf ? currentRoom.roomNsf : "Main.nsf");
	}

}

DM.service = {

	sFunc: null,
	eFunc: null,

	submit: function(fUnid,dUnid,svc,svcXml,sFunc,eFunc) {

		this.sFunc=sFunc || DM.service.success;
		this.eFunc=eFunc || DM.service.error;
		var cXml = svcXml || this.xml.common(svc,fUnid,dUnid,"");
		var xml = ''
		+ '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"'
		+ ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
		+ ' xmlns:xsd="http://www.w3.org/2001/XMLSchema">'
		+ '<soap:Header>'
//		+ '<userId>CN=Manager/o=agoelzert60</userId>'
		+ '<serviceVersion>8.0.0</serviceVersion>'
//		+ '<locale>en</locale>'
		+ '</soap:Header><soap:Body>'
		+ cXml
		+ '</soap:Body></soap:Envelope>';
		  
		try {
				dojo.io.bind({
				url: '/dm/services/DocumentService?do401=true',
				method: 'POST',
				sync: false,
				mimetype: 'text/xml', 
				contentType: 'text/xml',
//				encoding: "utf-8",
				postContent: xml,
				load: function(type, data) {DM.service.sFunc(fUnid,dUnid);},
				error: function(type, err) {DM.service.eFunc(err);}
				});
		}
		catch(e) {
			alert(e.message);
		}
	},

	success: function(fUnid,dUnid){this.reload();},
	error: function(e){alert(e.message);},

	reload: function() {
		if (typeof(FM.view) != "undefined" && typeof(Quickr81SupportUtil) != "undefined") {
			// use Ajax to refresh content
			FM.view.reqData();
		}
		else {
			location.reload();
		}
	}
}


DM.service.xml = {

	common: function(svc,fU,dU,att) {
		return '<'+svc+' xmlns="http://webservices.clb.content.ibm.com">'
		+ ' <path>/@P'+haikuName+'/@R'+DM.roomNsf()+'/@F'+fU+'/@D'+dU+att+'</path></'+svc+'>';
	},

	checkin: function(fU,dU,att) {
		return '<checkinDocument xmlns="http://webservices.clb.content.ibm.com">'
		+ ' <document path="/@P'+haikuName+'/@R'+DM.roomNsf()+'/@F'+fU+'/@D'+dU+'"/></checkinDocument>';
	}
}


DM.read = {
	// operations on a doc while in a "read scene":

	checkout: function(fUnid,dUnid) {
		DM.service.submit(fUnid,dUnid,"lockDocument",null,DM.read.loadDraft,DM.read.error);
	},

	checkin: function(fUnid,dUnid) {
		DM.service.submit(fUnid,dUnid,"",DM.service.xml.checkin(fUnid,dUnid,""),DM.read.loadIt,DM.read.error);
	},

	revert: function(fUnid,dUnid) {
		DM.service.submit(fUnid,dUnid,"cancelDocument",null,DM.read.loadIt,DM.read.error);
	},

	loadDraft: function(fUnid,dUnid) {
		// we need to get just-created draft's UNID
		var ajax = new QPAjax();
		ajax.RequestXML((location.href + "&Form=h_DocXml&nowebcaching"), DM.read.loadDraftFromXml);
	},

	loadDraftFromXml: function(data) {
		// get draft UNID from xml
		var fUnid = getTagValue(data, "qp_doc", "h_FolderUNID");
		var dUnid = getTagValue(data, "qp_doc", "h_DraftVersionUNID");
		if (fUnid != "" && dUnid != "") {
			// load draft
			DM.read.loadIt(fUnid,dUnid);
		}
		else {
			// reload published doc with link to draft
			location.reload();
		}
	},

	loadIt: function(fUnid,dUnid) {
		var folder=(fUnid=="" ? currentFolderStorage : fUnid);
		location.href=getAbsoluteServerRootURL(self)+"/"+getHaikuSubDir(self)+"/"+haikuName+"/"+DM.roomNsf()+"/"+folder+"/"+dUnid+"/?OpenDocument";

	},

	error: function(fUnid,dUnid) {
		 alert(QuickrLocaleUtil.getStringResource("DOC.ERROR").replace("{0}",dUnid));
	}

} // DM.read



DM.folder = {
	// operations on a doc while in a folder view:

	checkout: function(fUnid,dUnid) {
		DM.service.submit(fUnid,dUnid,"lockDocument");
	},

	checkin: function(fUnid,dUnid) {
		DM.service.submit(fUnid,dUnid,"",DM.service.xml.checkin(fUnid,dUnid,""));
	},

	revert: function(fUnid,dUnid) {
		DM.service.submit(fUnid,dUnid,"cancelDocument");
	},

	remove: function(fUnid,dUnid,bInToc,pubUnid,draftUnid,nChildren) { 
		var url="";
		if (nChildren != 0) {
			// can't delete doc with children
			alert(QuickrLocaleUtil.getStringResource("DOC.CANT"));
		}
		else if (draftUnid=="" && confirm(QuickrLocaleUtil.getStringResource("DOC.DELETETHIS"))) {
			// simple case: no draft
			DM.service.submit(fUnid,dUnid,"deleteDocument");
		}
		else if (confirm(QuickrLocaleUtil.getStringResource("DOC.DELETEBOTH"))) {
			// draft exists: this will remove both
			DM.service.submit(fUnid,dUnid,"deleteDocument");
		}
	}
}

DM.folder.list = {

	reload: function() {
		// Ajax reload
	}
}


DM.folder.details = {

	reload: function() {
		// Ajax reload
	}
}

function convertDateString(dateString){
		if(dateString==""){return dateString;}
		if(!(isHijri||isHebrew)) return dateString;
	var ret = "";
	var day;
	var month;
	var year;

	date = dateString.toString();
	var sDate = dateString.split(/\D/);
	if(haiku.h_Intl_DateFormat == haiku.kszDMY) {

		day = Number(sDate[0]);
		month = Number(sDate[1]);
		year = Number(sDate[2]);

	}else if(haiku.h_Intl_DateFormat == haiku.kszYMD){
		day = Number(sDate[2]);
		month = Number(sDate[1]);
		year = Number(sDate[0]);
	}else{
		day = Number(sDate[1]);
		month = Number(sDate[0]);
		year = Number(sDate[2]);
	}
	var date = new Date(year,month-1,day);
	if(isHijri){
	
		date = new dateHijri().gregorianToHijri(date);
	}
	if(isHebrew){
		date = new dateHebrew().gregorianToHebrew(date);
	
	}

	var sep = haiku.h_Intl_DateString;
	var year = date.getFullYear();
	var month =(((date.getMonth()+1) < 10) ? "0" : "") + (date.getMonth()+1);
	var day =((date.getDate() < 10) ? "0" : "") + date.getDate();
	if(haiku.h_Intl_DateFormat == haiku.kszDMY) {
		ret = day + sep + month + sep + year;
	}else if(haiku.h_Intl_DateFormat == haiku.kszYMD){
		ret = year + sep + month + sep + day;
	}else{
		ret = month + sep + day + sep + year;
	}
	return ret;
}


function returnToGregorian(dateString){
	if(dateString==""){return dateString;}
	if(!(isHijri||isHebrew)) return dateString;
	var ret = "";
	var day;
	var month;
	var year;

	date = dateString.toString();
	var sDate = dateString.split(/\D/);
	if(haiku.h_Intl_DateFormat == haiku.kszDMY) {

		day = Number(sDate[0]);
		month = Number(sDate[1]);
		year = Number(sDate[2]);

	}else if(haiku.h_Intl_DateFormat == haiku.kszYMD){
		day = Number(sDate[2]);
		month = Number(sDate[1]);
		year = Number(sDate[0]);
	}else{
		day = Number(sDate[1]);
		month = Number(sDate[0]);
		year = Number(sDate[2]);
	}
	var date;
	if(isHijri){
	
		date = new dateHijri(year,month-1,day).toGregorian();
	}
	if(isHebrew){
		date = new dateHebrew(year,month-1,day).toGregorian();
	
	}

	var sep = haiku.h_Intl_DateString;
	var year = date.getFullYear();
	var month =(((date.getMonth()+1) < 10) ? "0" : "") + (date.getMonth()+1);
	var day =((date.getDate() < 10) ? "0" : "") + date.getDate();
	if(haiku.h_Intl_DateFormat == haiku.kszDMY) {
		ret = day + sep + month + sep + year;
	}else if(haiku.h_Intl_DateFormat == haiku.kszYMD){
		ret = year + sep + month + sep + day;
	}else{
		ret = month + sep + day + sep + year;
	}
	return ret;
}



function dateParse(dataString) { 

	var re;
	
	if(haiku.h_Intl_DateFormat == haiku.kszYMD)
		re= /\d{4}\W\d{1,2}\W\d{1,2}/g;
	else 
		re= /\d{1,2}\W\d{1,2}\W\d{4}/g;
			
		return (dataString.replace(re,function($0,$1,$2){return(convertDateString($0));}));
 
}

function dateParseToGregorian(dataString) { 

	var re;
	
	if(haiku.h_Intl_DateFormat == haiku.kszYMD)
		re= /\d{4}\W\d{1,2}\W\d{1,2}/g;
	else 
		re= /\d{1,2}\W\d{1,2}\W\d{4}/g;
			
		return (dataString.replace(re,function($0,$1,$2){return(returnToGregorian($0));}));
 
}
