/** 
 * @description		prototype.js based context menu
 * @author        Juriy Zaytsev; kangax [at] gmail [dot] com; http://thinkweb2.com/projects/prototype/
 * @version       0.6
 * @date          12/03/07
 * @requires      prototype.js 1.6
*/

if (Object.isUndefined(Proto)) { var Proto = { } }
Proto.loadedMenus = [];

Proto.Menu = Class.create({
	initialize: function() {
	    Proto.loadedMenus.push(this);
	    this.menuId = (Proto.loadedMenus.length - 1);
	    
		var e = Prototype.emptyFunction;
		this.ie = Prototype.Browser.IE;
		this.options = Object.extend({
			selector: '.contextmenu',
			className: 'menu desktop',
			pageOffset: 25,
			fade: false,
			zIndex: 100,
			beforeShow: e,
			beforeHide: e,
			beforeSelect: e,
			idCallback: null,
			extraArgs: null
		}, arguments[0] || { });
		
        this.shim = new Element('iframe', {
         style: 'position:absolute;top:0;left:0;width:1px;height:1px;display:none',
         src: 'javascript:false;',
         frameborder: 0
        });

		this.containerInserted = false;
		this._idCallback = this.options.idCallback;
		this.options.fade = this.options.fade && !Object.isUndefined(Effect);
		this.container = new Element('div', {className: this.options.className, style: 'display:none'});
		this.arrMenuItems = new Array();
		this.options.menuItems.each(function(item)
		{
			if(!item.title)
			{
				item.title=item.name;
			}
			var link = '';
			if (!item.separator)
			{
    			link = Object.extend(new Element('a', {
							href: '#',
							title: item.title,
							className: (item.className || '') + (item.disabled ? ' disabled' : ' enabled')
						}), { _callback: item.callback})
						.observe('click', this.onClick.bind(this))
						.observe('contextmenu', Event.stop);
    			if(item.icon)
    			{
    				link.update(new Element("img", {
        			    src: item.icon
        			    }));
    				link.insert(new Element("img", {
        			    src: "images/transparent.gif",
        			    width:"7",
        			    height:"7"
        			    }));
    			}
				link.insert(item.name);
			}
			this.arrMenuItems.push(Object.extend(new Element('li', {className: item.separator ? 'separator' : ''}), { _displayCallback: item.displayCallback, _disabledCallback: item.disabledCallback}).insert(link));
		}.bind(this));

        this.container.observe('contextmenu', Event.stop);

        Event.observe(window, "load", this.onLoadInsert.bind(this));

		document.observe('click', this.hide.bind(this));
		
		$$(this.options.selector).invoke('observe', Prototype.Browser.Opera ? 'click' : 'contextmenu', function(e){
			if (Prototype.Browser.Opera && !e.ctrlKey) {
				return;
			}
			this.show(e);
		}.bind(this));
	},
	onLoadInsert: function() {
		if(!this.containerInserted)
		{
	        this.containerInserted = true;
            $(document.body).insert(this.container);
            if (this.ie) { $(document.body).insert(this.shim) }
		}
	},
	reattach: function() {
        this.onLoadInsert();
        $$(this.options.selector).invoke('stopObserving', Prototype.Browser.Opera ? 'click' : 'contextmenu', null);
        $$(this.options.selector).invoke('observe', Prototype.Browser.Opera ? 'click' : 'contextmenu', function(e){
         if (Prototype.Browser.Opera && !e.ctrlKey) {
             return;
         }
         this.show(e);
        }.bind(this));
	},
	closeAllOtherMenus: function(e) {
	    for (l=(Proto.loadedMenus.length-1); l>=0; --l) {
	        if ((l!=this.menuId) && Proto.loadedMenus[l]) {
	            Proto.loadedMenus[l].hide(e);
	        }
	    }
	},
	hide: function(e) {
		if (this.container.visible()) {
			this.options.beforeHide(e);
			if (this.ie) this.shim.hide();
			this.container.hide();
		}
	},
	show: function(e) {
	    this.closeAllOtherMenus(e);
        e.stop();
        this.onLoadInsert();
        this.options.beforeShow(e);
        while (this.container.hasChildNodes()) {
            this.container.removeChild(this.container.firstChild);
        }
		var list = new Element('ul');
		this.container.appendChild(list);
		var FirstInList = true;
		for(var i = 0; i<this.arrMenuItems.length; i++)
		{
			var item = this.arrMenuItems[i];
			if(item._displayCallback)
			{
				if(this._idCallback)
				{
					if(!item._displayCallback(this._idCallback(e)))
					{
						continue;
					}
				}
				else if(!item._displayCallback(e))
				{
					continue;
				}
			}
			if(item._disabledCallback)
			{
				if(this._idCallback)
				{
					if(item._disabledCallback(this._idCallback(e)))
					{
						var reg = new RegExp('(\\s|^)disabled(\\s|$)');
						item.firstChild.className=item.firstChild.className.replace(reg,' ') + " enabled";
					}
					else
					{
						var reg = new RegExp('(\\s|^)enabled(\\s|$)');
						item.firstChild.className=item.firstChild.className.replace(reg,' ') + " disabled";
					}
				}
				else
				{
					if(item._disabledCallback(e))
					{
						var reg = new RegExp('(\\s|^)disabled(\\s|$)');
						item.firstChild.className=item.firstChild.className.replace(reg,' ') + " enabled";
					}
					else{
						var reg = new RegExp('(\\s|^)enabled(\\s|$)');
						item.firstChild.className=item.firstChild.className.replace(reg,' ') + " disabled";
					}
				}
			}
			if(!FirstInList || item.className != 'separator')
			{
				list.appendChild(item);
				FirstInList = false;
			}
		}
		if(FirstInList)
		{
			return true;
		}
		var x = Event.pointer(e).x,
			y = Event.pointer(e).y,
			vpDim = document.viewport.getDimensions(),
			vpOff = document.viewport.getScrollOffsets(),
			elDim = this.container.getDimensions(),
			elOff = {
				left: ((x + elDim.width + this.options.pageOffset) > vpDim.width 
					? (vpDim.width - elDim.width - this.options.pageOffset) : x) + 'px',
				top: ((y - vpOff.top + elDim.height) > vpDim.height && (y - vpOff.top) > elDim.height 
					? (y - elDim.height) : y) + 'px'
			};
        this.container.setStyle(elOff).setStyle({zIndex: this.options.zIndex});
		if (this.ie) { 
            this.shim.setStyle(Object.extend(Object.extend(elDim, elOff), {zIndex: this.options.zIndex - 1})).show();
		}
        (this.options.fade && !this.ie) ? Effect.Appear(this.container, {duration: 0.25}) : this.container.show();
        this.event = e;
	},
	onClick: function(e) {
		e.stop();
		if (e.target._callback && !e.target.hasClassName('disabled')) {
			this.options.beforeSelect(e);
			if (this.ie) this.shim.hide();
			this.container.hide();
			if(this._idCallback)
			{
				e.target._callback(this._idCallback(this.event), this.options.extraArgs);
			}
			else
			{
				e.target._callback(this.event, this.options.extraArgs);
			}
		}
	}
})

function GetContainerMenuOptions(strContainerName) {
	if(strContainerName.match(/saved lightbox/))
	{
		var options = [
			{
				name: 'Edit',
				icon: 'menugraphics/edit.png',
				callback: EditAlbum
			},
			{
				name: 'Delete',
				icon: 'menugraphics/delete2.png',
				callback: DeleteAlbum
			}
		];
		return options;
	}
    var options = ContainerMenuOptions;
    if (strContainerName) options[0].name = 'Create sub-'+strContainerName;
    return options;
}
ContainerMenuOptions = [
	{
		name: 'Create sub-container',
		icon: 'menugraphics/add2.png',
		callback: AddSubAlbum
	},
	{
		name: 'Edit',
		icon: 'menugraphics/edit.png',
		callback: EditAlbum
	},
	{
		name: 'Edit Access',
		icon: 'menugraphics/folder_preferences.png',
		callback: EditContainerAccess
	},
	{
		name: 'Move',
		icon: 'menugraphics/folder_up.png',
		callback: MoveAlbum
	},
	{
		name: 'Delete',
		icon: 'menugraphics/delete2.png',
		callback: DeleteAlbum
	}
];

GU_MenuOptions = [
	{
		name: 'Edit',
		icon: 'menugraphics/edit.png',
		callback: EditGroupedUser
	},
	{
		name: 'Edit Access',
		icon: 'menugraphics/folder_preferences.png',
		callback: EditGroupedUserAccess
	},
	{
		name: 'Remove from group',
		icon: 'menugraphics/subtract2.png',
		callback: RemoveFromGroup
	},
	{
		name: 'Delete',
		icon: 'menugraphics/delete2.png',
		callback: SubmitDeleteUser
	}
];

AdminMenuOptions = [
	{
		name: 'Edit',
		icon: 'menugraphics/edit.png',
		callback: EditAdmin
	}
];
ZAMenuOptions = [
	{
		name: 'Download',
		icon: 'menugraphics/import1.png',
		callback: DownloadArchive,
		disabledCallback: function(nID) { return !IsArchiveDownloadable(nID); }
	}
];

GroupMenuOptions = [
	{
		name: 'Edit',
		icon: 'menugraphics/edit.png',
		callback: EditGroup
	},
	{
		name: 'Edit Access',
		icon: 'menugraphics/folder_preferences.png',
		callback: EditGroupAccess
	},
	{
		name: 'Delete',
		icon: 'menugraphics/delete2.png',
		callback: SubmitDeleteGroup
	}
];

var AssetMenuOptions = [];
var AlbumMenuOptions = [];

UserMenuOptions = [
	{
		name: 'Edit',
		icon: 'viewpicturegraphics/edit.png',
		callback: EditUser
	},
	{
		name: 'Edit Access',
		icon: 'admingraphics/treegraphics/folder_preferences.png',
		callback: EditUserAccess
	},
	{
		name: 'Delete',
		icon: 'viewpicturegraphics/delete.png',
		callback: SubmitDeleteUser
	}
];

ExternalUserMenuOptions = [
	{
		name: 'Edit',
		icon: 'viewpicturegraphics/edit.png',
		callback: EditExternalUser
	},
	{
		name: 'Delete',
		icon: 'viewpicturegraphics/delete.png',
		callback: SubmitDeleteExternalUser
	}
];

EventMenuOptions = [
	{
		name: 'Edit',
		icon: 'viewpicturegraphics/edit.png',
		callback: EditEvent
	},
	{
		name: 'Edit Access',
		icon: 'admingraphics/treegraphics/folder_preferences.png',
		callback: EditEventAccess
	},
	{
		name: 'Delete',
		icon: 'viewpicturegraphics/delete.png',
		callback: SubmitDeleteEvent
	}
];

arrAssets = new Array();
var arrLightboxAssets = null;
function IsArchiveDownloadable(nID)
{
	var row=$("ziparchives_" + nID);
	if(row)
	{
		var reg = new RegExp('(\\s|^)_success(\\s|$)');
		if(row.className && reg.test(row.className))
		{
			return true;
		}
	}
	return false;
}
function EditAsset(nID, extraArgs)
{
	var strDest = "editpicture.tlx?" + extraArgs + "&pictureid=" + nID;
	document.location.href=strDest;
}
function MoveAsset(nID)
{
	document.location.href = "movetocontainer.tlx?formpictureid=" + nID + "&returnurl=" + escape(document.location.href);
}
function MoveAlbum(nID)
{
	document.location.href = "movetocontainer.tlx?formcontainerid=" + nID + "&returnurl=" + escape(document.location.href);
}
function DeleteAsset(nID)
{
	if (confirm('Are you sure you want to delete this picture? Deleting a picture cannot be undone. The original data and any associated records for this picture will be removed.'))
	{
		document.location.href = 'dodelpic.tlx?pictureid=' + nID + '&returnurl=' + escape(document.location.href);
	}
}
function RotateAssetAnticlockwise(nID)
{
	document.location.href = "dorotate.tlx?formangle=0&pictureid=" + nID + "&returnurl=" + escape(document.location.href);
}
function RotateAssetClockwise(nID)
{
	document.location.href = "dorotate.tlx?formangle=1&pictureid=" + nID + "&returnurl=" + escape(document.location.href);
}
function AddHistoryNote(nID, extraArgs)
{
	var strDest = "addhistorynote.tlx?" + extraArgs + "&pictureid=" + nID + "&returnurl=" + escape(document.location.href);
	document.location.href=strDest;
}

function DownloadAssetOriginal(nID, extraArgs)
{
    document.location.href="dodownload.tlx?" + extraArgs + "&pictureid=" + nID + "&returnurl=" + escape(document.location.href);
}
function DownloadAssetWizard(nID, extraArgs)
{
    document.location.href="downloadwizard.tlx?" + extraArgs + "&pictureid=" + nID + "&returnurl=" + escape(document.location.href);
}

function RemoveFromGroup(nID)
{
	document.location.href='editgroupmembership.tlx?action=remove&forward=manageusers.tlx&userid=' + nID;
}

function EditAdmin(nID)
{
	document.location.href="editadmin.tlx?formuserid="+nID;
}
function EditUser(nID)
{
	document.location.href="edituser.tlx?formuserid="+nID;
}
function EditExternalUser(nID)
{
	document.location.href="editexternaluser.tlx?euid="+nID;
}
function EditEvent(nID)
{
	document.location.href="editevent.tlx?formeventid="+nID;
}
function EditUserAccess(nID)
{
	document.location.href="edituser.tlx?t=Edit Access&formuserid="+nID;
}
function EditEventAccess(nID)
{
	document.location.href="editevent.tlx?formcurrenttab=Edit Access&formeventid="+nID;
}
function EditGroupedUser(nID)
{
	document.location.href="editgroupuser.tlx?formuserid="+nID;
}
function EditGroupedUserAccess(nID)
{
	document.location.href="editgroupuser.tlx?formcurrenttab=Edit Access&formuserid="+nID;
}
function EditGroupAccess(nID)
{
	document.location.href="editgroup.tlx?formcurrenttab=Group%20Access&formgroupid="+nID;
}
function EditGroup(nID)
{
	document.location.href="editgroup.tlx?formgroupid="+nID;
}
function SubmitDeleteGroup(strGroupID)
{
    if (confirm("Are you sure you want to delete this group? All users will be moved out of this group. You can not undo this operation!"))
    {
        document.location.href = "dodelgroup.tlx?formgroupid="+strGroupID;
    }
}
function SubmitDeleteUser(strUserID)
{
    if (confirm("Are you sure you want to delete this user? All access rights, logs and other settings will be permanently removed. You can not undo this operation!"))
    {
        document.location.href = "dodeluser.tlx?returnurl="+escape(document.location.href)+"&formuserid="+strUserID;
    }
}
function SubmitDeleteEvent(strUserID)
{
    if (confirm("Are you sure you want to delete this event? All access rights, logs and other settings will be permanently removed. You can not undo this operation!"))
    {
        document.location.href = "dodelevent.tlx?returnurl="+escape(document.location.href)+"&formeventid="+strUserID;
    }
}
function SubmitDeleteExternalUser(strUserID)
{
    if (confirm("Are you sure you want to delete this external user? All access rights, logs and other settings will be permanently removed. You can not undo this operation!"))
    {
        document.location.href = "manageexternalusers.tlx?returnurl="+escape(document.location.href)+"&action=delete&euid="+strUserID;
    }
}
function EditAlbum(nID)
{
	document.location.href="editcontainer.tlx?containerid=" + nID + "&returnurl=" + escape(document.location.href);
}
function AddSubAlbum(nID)
{
	document.location.href="editcontainer.tlx?parentid=" + nID + "&returnurl=" + escape(document.location.href);
}
function DeleteAlbum(nID)
{
	if(confirm("Are you sure that you wish to delete this container and all subcontainers? This action cannot be undone!"))
	{
		document.location.href="dodelcontainer.tlx?containerid=" + nID + "&returnurl=" + escape(document.location.href);
	}
}
function DownloadArchive(nID)
{
	document.location.href="dodownloadziparchive.tlx?archiveid=" + nID;
}

function UploadToAlbum(nID)
{
	document.location.href="editalbum.tlx?formcurrenttab=Upload Files&containerid=" + nID + "&returnurl=" + escape(document.location.href);
}
function MergeAlbum(nID)
{
	document.location.href="mergealbum.tlx?formcontainerid=" + nID + "&returnurl=" + escape(document.location.href);
}
function ReduceAlbum(nID)
{
	document.location.href="doreducedir.tlx?formcontainerid=" + nID + "&returnurl=" + escape(document.location.href);
}

function EditContainerAccess(nID)
{
	document.location.href="editcontaineraccess.tlx?containerlist=" + nID + "&returnurl=" + escape(document.location.href);
}

function GetLightboxIDList(objCollectionNode)
{
	arrLightboxAssets = new Array();
	var objContentsNode = objCollectionNode.getElementsByTagName('contents')[0];
	if(objContentsNode)
	{
		var arrContents = objContentsNode.childNodes;
		var strHTML = '';
		if (arrContents.length > 0)
		{
			for (var i = 0; (i < arrContents.length); i++)
			{
				arrLightboxAssets.push(arrContents[i].getAttribute('id'));
			}
		}
	}
}

function InLightbox(nID)
{
	LIGHTBOX_GetContents(GetLightboxIDList);
	if(arrLightboxAssets)
	{
		for(var i = 0; i< arrLightboxAssets.length; i++)
		{
			if(arrLightboxAssets[i] == nID)
			{
				return true;
			}
		}
	}
	return false;
}

function OtherInLightbox(nID)
{
	LIGHTBOX_GetContents(GetLightboxIDList);
	if(arrLightboxAssets)
	{
		for(var i = 0; i< arrLightboxAssets.length; i++)
		{
			if(arrLightboxAssets[i] != nID)
			{
				return true;
			}
		}
	}
	return false;
}

function UnlinkAll(nID)
{
	if(confirm("Are you sure that you want to unlink all files related to this? This operation cannot be undone."))
	{
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.open("POST", "lightbox.tlx", true);
		xmlhttp.onreadystatechange = function()
		{
			if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
			{
				if (Sarissa.getParseErrorText(xmlhttp.responseXML) == Sarissa.PARSED_OK)
				{
					var strResult = xmlhttp.responseXML.documentElement.getElementsByTagName('result')[0].getAttribute('value');
					if (strResult == "OK")
					{
                        document.location.href = document.location.href;
					}
				}
			}
		};
		xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlhttp.send('action=clearlinkedassets&asset=' + nID);
	}
}

function UnLinkFileFrom(nID, nFrom)
{
	var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "lightbox.tlx", true);
    xmlhttp.onreadystatechange = function()
    {
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
        {
            if (Sarissa.getParseErrorText(xmlhttp.responseXML) == Sarissa.PARSED_OK)
            {
                var strResult = xmlhttp.responseXML.documentElement.getElementsByTagName('result')[0].getAttribute('value');
                if (strResult == "OK")
                {
                    document.location.reload();
                }
            }
        }
    };
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send('action=unlinkfromasset&pictureid=' + nID + '&asset=' + nFrom);
}
function LinkFileTo(nID, nTo)
{
	var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "lightbox.tlx", true);
    xmlhttp.onreadystatechange = function()
    {
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
        {
            if (Sarissa.getParseErrorText(xmlhttp.responseXML) == Sarissa.PARSED_OK)
            {
                var strResult = xmlhttp.responseXML.documentElement.getElementsByTagName('result')[0].getAttribute('value');
                if (strResult == "OK")
                {
                    document.location.reload();
                }
            }
        }
    };
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send('action=linktoasset&pictureid=' + nID + '&asset=' + nTo);
}


