/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2010                                    */
/*                                                                   */
/* 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 style="list-style-type:none; margin-left:0px;">';
	html += '<li id="' + this.name + '_name" class="cardName">' + this.displayName.replace(/\\\'/g, "'") +'</li>';
	html += '<li id="' + this.name + '_email">' + ceInsertMarkersforStaticString(this.email, 'ceEMAIL') + '</li>';
	html += '<li id="' + this.name + '_desc">' + this.description.replace(/\\\'/g,"'") + '</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";
	// SPR_WEBB7QGSDU
	menu.style.zIndex="1001";
	
	// Create unordered list
	html += '<div class="personMenu">';

	html += this.makeBizCard();

	html += '<div class="personMenuActions">';

	html += '<ul id="' + this.name + '_Top" style="list-style-type:none; margin-left:0px;"';
	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);
}

// Accessibility: To save focus which can be used after menu hide

var hash_savedFocus = {};


// ----------------------------------------------------------

function QP_ContextMenu_write()
{ 
	var ul = document.createElement("ul");
	ul.className="lotusActionMenu";
	//for a11y
	dojo.attr(ul,"tabindex",0);
 	if (this.extraClass)
 		ul.className += (" " + this.extraClass);
	ul.style.opacity="0.999999";
	if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ())){ul.style.visibility="hidden";}
	else if (document.body.dir=='rtl') {ul.style.right="-9999px";}
	else {ul.style.left="-9999px";}

	//a11y: handle escape key down
	dojo.connect(ul,"onkeydown",dojo.hitch(this,function(event){
		if(event.keyCode == dojo.keys.ESCAPE){
			
			dijit.focus(hash_savedFocus[this.name+"_Menu"]);
			var saveFocusNode = null;
			if(hash_savedFocus[this.name+"_Menu"])
				saveFocusNode = hash_savedFocus[this.name+"_Menu"].node;
			if(saveFocusNode && saveFocusNode.parentNode && saveFocusNode.parentNode.parentNode && saveFocusNode.parentNode.parentNode.id && saveFocusNode.parentNode.parentNode.id.substring(saveFocusNode.parentNode.parentNode.id.length-5)=="_Menu")
			{
				QP_ContextMenu_hideSubmenus(saveFocusNode.parentNode.parentNode.id);
			}else{
				QP_ContextMenu_hide();
			}						

			event.stopPropagation();
		}
	}));

	
	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");
				
				//a11y: hide menu when action item is triggered.
				dojo.connect(a,"onkeydown",function(event){
					if(event.keyCode == dojo.keys.ENTER)
						onBodyClick(event);
				});

				
				a.onmouseover = a.onfocus =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;
				var submenuHandler = function(){
					var smName=this.id.substring(this.id.lastIndexOf("__SUB__")+7);
					QP_ContextMenu_hideSubmenus(this.parentNode.parentNode.id);
					QP_ContextMenu_showSubmenu(this, smName);
				};
				// a11y: handle enter key to launch sub menu
				dojo.connect(a,"onkeydown",function(event){
					//console.debug("event.keyCode="+event.keyCode);
					if(event.keyCode == dojo.keys.ENTER)
						submenuHandler.call(this);
				});
				a.onmouseover = submenuHandler;
			}

			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, inx, iny, bPersonMenu)
{
	bPersonMenu = (typeof bPersonMenu == "undefined" ? false : bPersonMenu);

	if (inx && iny) {
		// coordinates specified
		g_pageX = inx;
		g_pageY = iny;
	}
	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;

		var mScrollPos = document.documentElement.scrollTop;
		if (typeof(window.innerWidth)=='number') {
			//Non-IE
                        if (mScrollPos==0 && window.pageYOffset!=0){ mScrollPos = window.pageYOffset; }
			if (window.innerHeight < (g_pageY - mScrollPos + mHeight)) {
                               g_activeMenu.style.top = g_pageY + (window.innerHeight - (g_pageY - mScrollPos + mHeight) - 2) + "px";
			} else {
      		               g_activeMenu.style.top =  (g_pageY) + "px";
                        }
		}
		else if(document.documentElement && document.documentElement.clientHeight) {
			//IE 6+ in standards compliant mode
			mScrollPos = document.documentElement.scrollTop;
			if (document.documentElement.clientHeight < (g_pageY - mScrollPos + mHeight)) {
                               g_activeMenu.style.top = g_pageY + (document.documentElement.clientHeight - (g_pageY - mScrollPos + mHeight) - 2);
			} else {
       		               g_activeMenu.style.top =  (g_pageY + document.body.scrollTop);
                        }
		}
		else if (document.all) {
			// IE
			mScrollPos = document.documentElement.scrollTop;
			if (document.documentElement.clientHeight < (g_pageY - mScrollPos + mHeight)) {
                               g_activeMenu.style.top = g_pageY + (document.documentElement.clientHeight - (g_pageY - mScrollPos + mHeight) - 2);
			} else {
       		               g_activeMenu.style.top =  (g_pageY + document.body.scrollTop);
                        }
		}


		if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ()))
		{
		if (document.body.clientWidth < (mWidth+document.body.scrollWidth -g_pageX - mWidth)){
			if (g_pageX < mWidth) {
				g_activeMenu.style.right = (document.body.clientWidth - mWidth - 2) + "px";
			} else {
				g_activeMenu.style.right = (document.body.clientWidth - g_pageX - 2) + "px";
			}
		}
		else {
			if (g_pageX < mWidth) {
				g_activeMenu.style.right = (document.body.scrollWidth - mWidth ) + "px";	
			} else {
				g_activeMenu.style.right = (document.body.scrollWidth - g_pageX ) + "px";
			}
		}
	
		}
		else if(!bPersonMenu && document.body.dir=='rtl')
		{
			if (g_pageX + document.body.scrollLeft < mWidth)
				left = (document.body.scrollLeft - mWidth - 2);
			else
				left = (document.body.scrollLeft - g_pageX);
			g_activeMenu.style.right = Math.min(0,left) + "px";
		}
		else
		{
			var RTLV = 0;
			if(document.body.dir=='rtl') {RTLV = mWidth;}
			if (document.body.clientWidth < (g_pageX + document.body.scrollLeft + mWidth))
				left = (document.body.clientWidth - mWidth - 2 - RTLV);
			else
				left = (g_pageX + document.body.scrollLeft-RTLV);
			g_activeMenu.style.left = Math.max(0,left) + "px";
		}

		g_activeMenu.parentNode.style.zIndex = 1000 + g_activeIdx;
		g_activeMenu.style.display="block";
		g_activeMenu.style.visibility="visible";
		
		//a11y: save the focus and set focus on active Menu.
		hash_savedFocus[g_activeMenu.id] = dijit.getFocus(this);
		g_activeMenu.focus();
	}

	// Hide menu when click outside or timer elapses
	dojo.connect(document, "onmouseup", "onBodyClick");
//	dojo.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) {
		var bPersonMenu = false;
		if (typeof g_visibleMenu[g_activeIdx].firstChild != "undefined") {
			if (g_visibleMenu[g_activeIdx].firstChild.className == "personMenu") {
				bPersonMenu = true;
			}
		}
		if((document.body.dir=='rtl')&&(h_ClientBrowser.isIE ())){g_visibleMenu[g_activeIdx--].style.visibility="hidden";}
		else if (!bPersonMenu && document.body.dir=='rtl') g_visibleMenu[g_activeIdx--].style.right="-9999px";
		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.visibility="hidden";}
		else if (document.body.dir=='rtl') g_visibleMenu[g_activeIdx--].style.right="-9999px";
		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.connect(span, "onmouseover", "onDocMouseOver");
						dojo.connect(span, "onmouseout", "onDocMouseOut");
					}
				}
				else if (bUserNames && (span.className=="h-user-anchor" || span.className=="vcard"))
				{
					var aTags = span.getElementsByTagName("a");
					if (aTags[0]) {
 						dojo.connect(span, "onmouseover", "onPersonMouseOver");
 						dojo.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.connect(span, "onmouseover", "onMyPlacesMouseOver");
						dojo.connect(span, "onmouseout", "onMyPlacesMouseOut");
					}
				}
				else if (bDocuments && span.className=="h-attachments-anchor") 
				{
					makeAttachmentsMenu(span.id, span.getAttribute("attachments"));
					dojo.connect(span, "onmouseover", "onAttMouseOver");
					dojo.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.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;
	if(!img){
		img = e;
	}
	var pos = findPos(img);
	QP_ContextMenu_show(img.parentNode.id,true,pos[0],(pos[1]+img.offsetHeight));
	try{
		e.preventDefault();
	}
	catch(ex){
	}
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// EVENT HANDLER FOR "CREATE" MENU
//
// NOTE: Not supported in 8.1/8.2!
// 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.xhrGet ({
				url: url + "&Form=h_DocXml&nowebcaching",
				handleAs: "xml",
				load: function(data) {showDocContextMenu(a.id,a.href,data,btn,imgSrc,pos[0],(pos[1]+btn.offsetHeight));}
			});

			btn.src = "/qphtml/html/common/ajax_loader.gif";
		}
		catch(e) {
			window.location.reload();
		}
	}
}

function showDocContextMenu(name,url,data,img,imgSrc,x,y)
{
	//if they are an editor but the doc is currently locked, they should not see all of the context menu items
	var currentUserAccess_saved = window.currentUserAccess;
	if ( getTagValue(data, "qp_doc", "h_DraftVersionUNID") != "" && window.currentUserAccess == 4 ) window.currentUserAccess = 3;
	
	img.src=imgSrc;
	makeDocContextMenu(name,url,data);
	QP_ContextMenu_show(name,true,x,y);
	
	window.currentUserAccess = currentUserAccess_saved;
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// 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 MSG_CLICK_FOR_USERPROFILE = QuickrLocaleUtil.getStringResource("QP_STRINGS.MSG_CLICK_FOR_USERPROFILE");
	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("alt", MSG_CLICK_FOR_USERPROFILE);
		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 {
			// title attribute is DN
			var dn=QP_ContextMenu_fixName(a.title);
			var pos = findPos(btn);
			var imgSrc = btn.src;

			dojo.xhrGet ({
				url: a.href + "&Form=h_MemberXml&nowebcaching",
				handleAs: "xml",
				load: function(data) {showPersonContextMenu(dn,a.href,data,btn,imgSrc,pos[0],(pos[1]+btn.offsetHeight));}
			});
			
			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,true);
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// 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.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
//
// ~~~~~~~~~~~~~~~~~~~~~~~~


// Generate the <span> containing a document or folder anchor and whatever else is needed
// to associate a context menu with that element.

// SPR #MPUL7K2KWM : exe file download problem in  2008/10/30 
var Browser = 'isNonIE'
if((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) 
	Browser = 'isIE'; 
	
function GenerateAttachmentsAnchor(unid,name,size,form)
{
	var aMSO = [	G_FormIDs.CreateMSWordFormUNID, 
			G_FormIDs.CreateMSExcelFormUNID, 
			G_FormIDs.CreateMSPowerPointFormUNID
	];
	
	var html="";
	
   	// SPR XHKG76WAJ9: filter unwanted attachments
	if ( name.indexOf('/') > -1 ) {
		//SPR: #RTIN7NRHLY
		var aN = name.split('/');
		var aS = size.split(',');
		
		if (aMSO.indexOf(form) > -1) {
			// MS Office doc: real attachment is first in list
			name = aN[0]
			size = aS[0];
			
		} else {
			// Filter out all the TMPxxxx files from the list (generated from quickr backend)
			var aN_temp = new Array();
			var aS_temp = new Array();

			for (i=0; i<aN.length; i++) {
				if (!QuickrGeneralUtil.isInternalFileName(aN[i],form)) {
					aN_temp.push( aN[i] );
					aS_temp.push( aS[i] );
				}
			}
			if (form == G_FormIDs.HTMLPageFormUNID) {
				name = aN_temp[aN_temp.length-1];
				size = aS_temp[aS_temp.length-1];
				if (typeof(name) == "undefined") {
					name = "";
				}
			} else {
				name = aN_temp.join("/");
				size = aS_temp.join(",");
			}
		}		
	}

	//SPR: #RTIN7NRHLY
	if (name.indexOf('/') < 0) {
		// There's only one attachment
		szAlt = QuickrGeneralUtil.encodeEntities(name);
		szAlt = size ? QuickrLocaleUtil.getStringResource("CONTEXT.DOWNLOADSIZE").replace("{0}",szAlt).replace("{1}",size) : QuickrLocaleUtil.getStringResource("CONTEXT.DOWNLOAD").replace("{0}",szAlt);
		name = encodeURIComponent(name);
		var linkurl = generateAttachmentLinkHref(unid,name);
		var linktarget = "";
		if (linkurl.indexOf("QuickrSupportUtil") == -1) {
			linktarget = " target=\"_blank\" ";
		}
		html = '<a href="' + linkurl + '"'
			+ ' alt="'+szAlt+'" title="'+szAlt+'" ' + linktarget + '>'
			+ '<img style="border:none;" src="/qphtml/html/common/download.gif" alt="'+szAlt+'"/>'
			+ '<img alt="" 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"/>'
			+ '<a href="javascript:;" onclick="javascript:onAttContextMenu(this)" ><img class="h-contextMenu-icon" '
			+ 'title="' + QuickrLocaleUtil.getStringResource("CONTEXT.ATTACHMENTS") + '" alt="' 
			+ QuickrLocaleUtil.getStringResource("CONTEXT.ATTACHMENTS") 
			+ '" src="/qphtml/html/common/menu_u.gif"/></a>'
			+ '</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(';');
		//SPR: #RTIN7NRHLY
		var aN = unescape(a[0]).split('/');
		var aS = unescape(a[1]).split(',');
		for (i=0; i<aN.length; i++) {
			// SPR #MPUL7K2KWM : exe file download problem in  2008/10/30 
			if(aN[i].indexOf('\.exe') > 0 && Browser == 'isIE'){
				menu.addItem(aN[i],
							 '../../$defaultview/' + unid + '/$File/' + encodeURIComponent(aN[i]) ,
							 generateAttachmentLinkHref(unid,aN[i]),
							 "", null, "/qphtml/html/common/doc_download.gif",
							 QuickrLocaleUtil.getStringResource("CONTEXT.DOWNLOADBYTES").replace("{0}",aS[i]));
			}
			else{
				var szUrl = generateAttachmentLinkHref(unid,aN[i]);
				var szTarget = "";
				if (szUrl.indexOf("QuickrSupportUtil") == -1) {
					szTarget = "_blank";
				}
				menu.addItem(aN[i],
							 szUrl, szTarget, null, "/qphtml/html/common/doc_download.gif",
							 QuickrLocaleUtil.getStringResource("CONTEXT.DOWNLOADBYTES").replace("{0}",aS[i]));  
			}
			
		}
		menu.write();
	}
}

function generateAttachmentLinkHref (docid, fileName) {
		
	return QuickrGeneralUtil.getDownloadLink(docid, fileName);
		
}


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// 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 MSG_CLICK_FOR_USERPROFILE = QuickrLocaleUtil.getStringResource("QP_STRINGS.MSG_CLICK_FOR_USERPROFILE");
	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">'
			 + '<a href="' + url + '" title="' + szDN + '">' + szCN + memPostfix + '</a>'
			 + '<img alt="' + MSG_CLICK_FOR_USERPROFILE + '" title="' + MSG_CLICK_FOR_USERPROFILE + '" 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 = QuickrLocaleUtil.getStringResource("QP_CONTEXT_MENU.LABEL_YES");

// 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.replace(new RegExp("<","g"),"&lt;") + '</a>');
	span += '<a href="javascript:;" onclick="javascript:onDocContextMenu(this);" ><img class="h-contextMenu-icon" title="' + QuickrLocaleUtil.getStringResource("CONTEXT.OPTIONS") + '" alt="' + QuickrLocaleUtil.getStringResource("CONTEXT.OPTIONS") + '" src="/qphtml/html/common/menu_u.gif"/></a>';
	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 '';
		}
	}
}

