
var lightBox;
var loc;
var winHeight;
var winWidth;

// Creates a lightbox displaying the contents of the URL passed in.
function createWorkbenchDialogFromUrl(initialUrl, windowWidth, windowHeight) {
	var dWidth = 400;
	var dHeight = 450;
	if(windowWidth) {
		dWidth  = windowWidth;		
	}
	if(windowHeight) {
		dHeight = windowHeight;		
	}	
	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnCall, width:dWidth, height:dHeight});
}

// Creates a lightbox displaying the contents of the URL passed in.
function createSampleListDialogFromUrl(initialUrl) {
	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnCall, width:500, height:250});
}

// Creates a lightbox displaying the contents of the URL passed in.
function createDialogFromUrl(initialUrl, windowWidth, windowHeight) 
{
	//because of the use of curry for the ajax method - we need the window height and window width 
	//set to the global variables
	winHeight = windowHeight;
	winWidth  = windowWidth;

	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnDownload, width:windowWidth, height:windowHeight});
}

// Creates a lightbox displaying the HTML passed in.  
function createWorkbenchDialogFromHtml(html) {
	lightBox = new LITBox("", "", "", html, {type:"window", overlay:true, resizable:false, opacity:1, callback:returnCall, width:400, height:450});
}

// Creates a lightbox to be used in a specific situation.
function createWorkbenchDialogFromUrlForUnsavedItems(initialUrl, formName, selectionItemName, windowWidth, windowHeight) {
	var dWidth = 400;
	var dHeight = 450;
	if(windowWidth) {
		dWidth  = windowWidth;		
	}
	if(windowHeight) {
		dHeight = windowHeight;		
	}
	var selectedIds = getCheckedItems(formName, selectionItemName);
	initialUrl += "&ids=" + selectedIds;
	loc = '/brc/workbench.do?method=WorkbenchDetail';
	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnLoginWorkbenchRedirect.curry(null), width:dWidth, height:dHeight});
}

// Creates a lightbox that can handle file upload fields.
function createUploadDialogFromUrl(initialUrl) {
	loc = '/brc/workbench.do?method=WorkbenchDetail';
	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnCall, width:400, height:450, submitForm:false});
}

// Creates a lightbox displaying the contents of the URL passed in.  On success, it updates the divs passed in the refreshIds parameter.
function createRefreshDialogSized(initialUrl, refreshIds, windowWidth, windowHeight) {

	//because of the use of curry for the ajax method - we need the window height and window width set to the global variables
	winHeight = windowHeight;
	winWidth  = windowWidth;

	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnReplace.curry(refreshIds, '/brc/navigationOnly.do'), width:windowWidth, height:windowHeight});
}

// Creates a lightbox displaying the contents of the URL passed in.  On success, it updates the divs passed in the refreshIds parameter.
function createRefreshDialog(initialUrl, refreshIds, windowWidth, windowHeight) {
	var dWidth = 400;
	var dHeight = 450;
	if(windowWidth) {
		dWidth  = windowWidth;		
	}
	if(windowHeight) {
		dHeight = windowHeight;		
	}
	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnReplace.curry(refreshIds, '/brc/navigationOnly.do'), width:dWidth, height:dHeight});
}

// Creates a lightbox displaying the contents of the URL passed in.  On success, it updates the divs passed in the refreshIds parameter.
function createWorkbenchRefreshDialog(initialUrl, refreshIds, windowWidth, windowHeight) {

	//because of the use of curry for the ajax method - we need the window height and window width set to the global variables
	winHeight = windowHeight;
	winWidth  = windowWidth;
	
	loc = '/brc/workbench.do?method=WorkbenchDetail';
	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnReplace.curry(refreshIds, loc), width:windowWidth, height:windowHeight});
}

// Creates a lightbox displaying the contents of the URL passed in.  On success, it updates the divs passed in the refreshIds parameter.
function createWorkbenchRefreshFromUrlDialog(initialUrl, refreshIds, windowWidth, windowHeight, refreshUrl) {

	//because of the use of curry for the ajax method - we need the window height and window width set to the global variables
	winHeight = windowHeight;
	winWidth  = windowWidth;
	loc=refreshUrl;
	
	lightBox = new LITBox("", "", initialUrl, "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnReplace.curry(refreshIds, loc), width:windowWidth, height:windowHeight});
}

// Creates a lightbox displaying the HTMl passed in.  On success, it updates the divs passed in the refreshIds parameter.
function createRefreshDialogFromHtml(refreshIds, html, url) 
{
	if(winHeight == null)
		winHeight = 450;
					
	if(winWidth == null)
		winWidth = 400;

	lightBox = new LITBox("", "", "", html, {type:"window", overlay:true, resizable:false, opacity:1, callback:returnReplace.curry(refreshIds, url), width:winWidth, height:winHeight});
} 

// Creates a lightbox displaying the contents of the URL passed in.  On success, it calls the returnLoginWorkbenchRedirect method.
function createWorkbenchLoginDialogFromUrl(decorator) {
	lightBox = new LITBox("", "", '/brc/user.do?method=PreLogin', "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnLoginWorkbenchRedirect.curry(decorator), width:400, height:450});
}

//Creates a lightbox displaying the contents of the URL passed in.  On success, it calls the returnLoginWorkbenchRedirect method.
function createBlastLoginDialogFromUrl(decorator) {
	lightBox = new LITBox("", "", '/brc/user.do?method=PreLogin', "", {type:"window", overlay:true, resizable:false, opacity:1, callback:returnLoginBlastRedirect.curry(decorator), width:400, height:450});
}

// Creates a lightbox displaying the HTMl passed in.  On success, it calls the returnLoginWorkbenchRedirect method.
function createWorkbenchLoginDialogFromHtml(html) {
	lightBox = new LITBox("", "", "", html, {type:"window", overlay:true, resizable:false, opacity:1, callback:returnLoginWorkbenchRedirect.curry(null), width:400, height:450});
}

// Handles a lightbox error (server 500)
function handleError(data) {
    createWorkbenchDialogFromUrl('/brc/messageDialog.do?messageDialog=An error occurred with the action you were attempting to perform.');
}

// Return callback for a standard lightbox.  If there is more HTML to be displayed, the
// lightbox is populated with that HTML.  If not, remove the lightbox.
function returnCall(responseText) {
	if (responseText !== " ") {
		createWorkbenchDialogFromHtml(responseText);
	} else {
		lightBox.remove();
	}
}

function returnDownload(responseText) {
		lightBox.remove();
}

// Replaces divs in a page.  It makes an AJAX call to the url provided.  The HTML returned from that call is examined
// to find the divs with IDs specified in the refreshIds parameter.  The HTML found in those divs is then used to
// replace the HTML in the same divs in the page the user sees.
function returnReplace(refreshIds, url, responseText) {

    // Close the existing lightbox
    try {
	   lightBox.remove();
	} catch(e) { }	
	
	// If there is more HTML to be displayed to the user, create a new lightbox with that HTML
	if (responseText !== " ") {	
		createRefreshDialogFromHtml(refreshIds, responseText, url);
	} 		


    // Handle getting HTML for the URL provided and updating divs based on the HTMl returned
	var ids = refreshIds.split(',');
	var options = {
		method:"get", 
		asynchronous:true, 
		onSuccess:function (response) {
			var div= new Element('div');
 			div.innerHTML=response.responseText;
 			ids.each(function(id) {				
 				id = id.strip();
				if($(id)) {
	 				var newSection = div.select($(id).nodeName);			
	 				var newDiv;
	 				newSection.each(function(e){
	 					
	 					if(e.id == id) {
	 						newDiv = e;
	 					}
	 				});
	 				$(id).replace(newDiv);
 				}
 			});
 			initHome();
 			// Update the workbench section of the ViPR family 
 			// home page if user just logged in
		    if($('yourAccountMenuItem').innerHTML.indexOf('ACCOUNT') > 0) {
		      switchViprFamilyHomePageOnLogin();
		    }	 			
		}};	
		
		// Strip out # and add a date to avoid caching issues with IE
		url = new String(url).gsub('#', '');
		if(url.include('?')) {
			new Ajax.Request(url + '&' + Date(), options);
		} else {
			new Ajax.Request(url + '?' + Date(), options);		
		}	
}

// Return callback for when a user clicks the left navigation menu option to log into their workbench.   
// Handles the result of the user attempting to log in for that situation.
function returnLoginWorkbenchRedirect(decorator, responseText) {
	if (responseText !== " ") {
	    // HTML was returned, so there is another page to display to the user.  Show that page.
		createWorkbenchLoginDialogFromHtml(responseText);
	} else {
	    // No HTML was returned, so close the lightbox and forward to the workbench detail (since that's where the user wanted to go)
        try {
		  lightBox.remove();
	     } catch(e) { }
	     if(decorator) {
	    	 window.location = 'workbench.do?method=WorkbenchDetail&decorator=' + decorator;
	     }else {
	    	 window.location = 'workbench.do?method=WorkbenchDetail';
	     }
	}	
}

//Return callback for when a user clicks the left navigation menu option to log into their workbench.   
//Handles the result of the user attempting to log in for that situation.
function returnLoginBlastRedirect(decorator,responseText) {
	if (responseText !== " ") {
	    // HTML was returned, so there is another page to display to the user.  Show that page.
		createWorkbenchLoginDialogFromHtml(responseText);
	} else {
     try {
		  lightBox.remove();
	     } catch(e) { }
     window.location = 'blast.do?method=ShowCleanInputPage&decorator=' + decorator;
	}
}

// Makes an AJAX call to log out the user.  When finished, it updates the navigation menus to reflect the user being logged out
function logout() {
	var options = {
		method:"get", 
		asynchronous:false, 
		onSuccess:function() {
		   returnReplace('workbenchNavigation, welcomeMessage, yourAccountMenuItem', '/brc/navigationOnly.do', ' ');
		},
		onFailure:function(){
			alert("Failure in Ajax Request - check Java Code for exceptions!");
		} 			
	};
	new Ajax.Request("j_acegi_logout.acegi", options);
	
	// Update Vipr Family home page (if we're on that page)
	switchViprFamilyHomePageOnLogout();
}

// Makes an AJAX call to verify that the user is allowed to proceed with an action.  If 'Allowed' is return, 
// proceed to the URL provided.  If not, display an alert with an error.
function verifyCombination(formName, selectionItemName, urlForCombinationCheck, urlForCombineAction, urlForRefresh, refreshableAreas, wWidth, wHeight) {
	var selectedIds = getCheckedItems(formName, selectionItemName);
	var windowWidth = wWidth;
	var windowHeight = wHeight;
	var options = {
		method:"post",
		parameters:{ids: selectedIds},
		asynchronous:true,
		onSuccess:function(response) {
			if (response.responseText == 'Allowed') 
			{
				if(windowHeight == null)
					windowHeight = 450;
					
				if(windowWidth == null)
					windowWidth = 400;
			
				createWorkbenchRefreshFromUrlDialog(urlForCombineAction, refreshableAreas, windowWidth, windowHeight, urlForRefresh);
			} 
			else {
				alert(response.responseText);
			}
		}
	};
	
	new Ajax.Request(urlForCombinationCheck, options);
}

// Finds all checkboxes with an ID of selectedItems on the page.  Adds the IDs for those that are checked to a comma separated list.
// The comma separated list is then placed into a hidden field.
// This is called by a lightbox when it needs to know which checkboxes have been selected.
// If lightbox also need to submit the form, then supply the submitFormId
getSelectedCheckboxes = function(enclosedFormId, submitFormId) 
{
	var allSelectionCheckboxes = document.getElementsByName("selectedItems");
	var enclosedForm = $(enclosedFormId);
	if(enclosedForm) {
		allSelectionCheckboxes = $$('#' + enclosedForm.id + ' input[name=selectedItems]');
	}
	
	var list = '';	
	for (i = 0; i < allSelectionCheckboxes.length; i++) {
	    if(allSelectionCheckboxes[i].checked) {
		    var checkboxValue = allSelectionCheckboxes[i].value;
		    if(list.length==0) {
		       list =  list + checkboxValue;
		    } else {
		       list =  list + '#%^' + checkboxValue;
		    }
	    }
	    if(allSelectionCheckboxes[i].id == 'selectionSpecialInstructions') {
	    	if($('selectionSpecialInstructions')) {
	    	  list = list + '#%^' + $('selectionSpecialInstructions').value;
	    	}
	    }
	}
	
	var selectedItemsListField = $("selectedItemsList");
	if(selectedItemsListField){
		selectedItemsListField.value=list;
	}
	var vDownloadSelectedItemsList = $("vDownloadSelectedItemsList");
	if(vDownloadSelectedItemsList){
		vDownloadSelectedItemsList.value=list;
	}
	if($(submitFormId)) {
		$(submitFormId).submit();
	}
}

// Makes an AJAX call to verify that the user is allowed to proceed with an action.  If 'Allowed' is return, 
// proceed to the URL provided.  If not, display an alert with an error.
function verifyWorkingSet(formName, selectionItemName, urlForUploadCheck, urlForUploadAction, action) {
	var r = confirm("Do you want to " + action + " selected items?");
	if (r==true){
		var selectedIds = getCheckedItems(formName, selectionItemName);
		var options = {
			method:"post",
			parameters:{ids: selectedIds},
			asynchronous:true,
			onSuccess:function(response) {
				if (response.responseText == 'Allowed') 
				{
					  window.location = urlForUploadAction;
				} 
				else {
					alert(response.responseText);
				}
			}
		};
		
		new Ajax.Request(urlForUploadCheck, options);
	}
}
//Makes an AJAX call to verify that the user is allowed to perform manage item
function verifySharingItem(formName, selectionItemName, urlForUploadAction, decorator) {
	var selectedIds = getCheckedItemsInArray(formName, selectionItemName);	
	if(selectedIds.size() <= 0) {
		alert('At least one checkbox need to be checked!');
		return false;
	} else {
		// Need to invoke this in an ajax call first, so the whole lightbox is working under an HTTPRequest instead of a regular request('workbench.do?method=WorkbenchDetail')
		lightBoxInHttpRequest(urlForUploadAction + '&sharableIds=' + selectedIds.join(), 'workbenchHomeWorkingSets, workbenchNavigation', null, 520, 500, decorator);
	}
}

function lightBoxInHttpRequest(url, refreshIds, refreshUrl, width, height, decorator) {
	if(refreshIds && !refreshUrl) {
		refreshUrl = window.location;
	}
	// Need to invoke this in an ajax call first, so the whole lightbox is working under an HTTPRequest instead of a regular request
	var options = {
			method:"post",
			asynchronous:true,
			onSuccess:function(response) {
				if(response.responseText.isJSON()) {
					var resp = response.responseText.evalJSON();
					if (resp.status == 'Allowed') 
					{
						createWorkbenchRefreshFromUrlDialog(url, refreshIds, width, height, refreshUrl);
					}
				}else {
					if(response.responseText.indexOf('class="requiredForLogin"') > 0){
						createWorkbenchLoginDialogFromUrl(decorator);
					}else {
						alert(response.responseText);
					}
				}
			},
			onException:function(response){
				lightBox = new LITBox(response.responseText, "", "", "", {type:"alert"  , overlay:true, resizable:false, opacity:1, strongRemove:true, callback:lightBox.remove, width:500, height:250});
			}
		};	
		new Ajax.Request('/brc/workbenchWorkingSet.do?method=dummyAjaxRequest', options);
}