/**
 @fileoverview toolbar.js has functions and objects that are used in the toolbar jsp file.
 @author Craig Warren
*/

/**
 i18n
*/
var ItemsToAddBoxBibsToAddCaption = "Bibs to add";

/**
 i18n
*/
var ItemsToAddBoxItemsToAddCaption = "Items to add";

/**
 i18n
*/
var ItemsToAddBoxBibsNotToAddCaption = "Bibs that will not be added";

/**
 i18n
*/
var ItemsToAddBoxItemsNotToAddCaption = "Items that will not be added";

/**
 i18n The text that goes in the input box for creating a new list,
  prompts the user to enter a new list name
*/
var DefaultCreateNewListText = "Enter New List";

/**
 i18n The text to use for the link or button to create a new list
*/
var createNewListValue  = "Create";

/**
  i18n text in the alert box that is displayed when an error
  occurs while trying to add  a list
*/
var ErrorAddingNewListText = "Error adding List";

/**
  i18n text in the alert box that is displayed when an error
  occurs while trying to add to a list
*/
var ErrorAddingToList = "Error while adding to My List";


/**
  i18n text used when no bibs or items are selected when they are required to be
*/
var ErrorNoBibsItemsSelected = "No bibs or items selected";

/**
 i18n text used when nothing is selected and is required to be
*/
var ErrorNothingSelected =  "Nothing is selected.";

/**
 i18n text to tell users that items can't be emailed
*/
var ErrorCannotEmailItems =  "You must select a title. Individual copies cannot be emailed."

/**
 i18n error message while trying to send email
*/
var ErrorSendingEmail = "Error while trying to send email";

/**
 i18n Invalid email address
*/
var ErrorInvalidEmailAdressTo = 'Invalid email address in the "To" field';


/**
 i18n error message while trying to add to alerts
*/
var ErrorAddingAlerts = "Error while adding alerts";

/**
 i18n success message while trying to add to alerts
*/
var SuccessAddingAlerts = "Alerts added successfully.  Go to Preferences Tab - Alerts to Manage Alerts.";


/**
 i18n error messages if requests are not allowed
*/
var ErrorBatchRequestsNotAllowed = "Batch requests are not allowed.";
var ErrorBibRequestsNotAllowed = "Bib-level requests are not allowed.";
var ErrorOneOrAllItemsRequestsNotAllowed = "One or more of the selected items is not requestable.";
var ErrorItemRequestsNotAllowed = "Item-level requests are not allowed.";
var ErrorBibMyListNotAllowed = "Adding of bibs to My List is not allowed.";
var ErrorPageHasProblemRecords = "This page contains records that can not be added to My List.";
var ErrorItemMyListNotAllowed = "Adding of items to My List is not allowed.";
var ErrorListAlreadyExists = "A list with this name already exists.";

var bibMyListAllowed = true;        
var itemMyListAllowed = true;
var tempListId = '-1';

/**
The ItemsToAddBox object is used with the HTML div tag in the toolbar jsp file.
@class
It is used to help display the bib and items that will be added and not added to the my list
4 members are set and meant to be override for internationalization.<br>
<i>var itemsToAddBox = new ItemsToAddBox();<br>
itemsToAddBox.ItemsToAddCaption = "Artículos a agregar"; <br></i>
* @constructor
*/
function ItemsToAddBox(){
    // Constants to use for the ItemsToAddBox

    /**
     i18n Text that goes above the bibs to add table, set this for internationalization
     @type String
    */
    this.BibsToAddCaption = ItemsToAddBoxBibsToAddCaption;
    
    /**
     i18n Text that goes above the items to add table, set this for internationalization
     @type String
    */
    this.ItemsToAddCaption = ItemsToAddBoxItemsToAddCaption;
    
    /**
     i18n Text that goes above the bibs that aren't going to be added table,
     set this for internationalization
     @type String
    */
    this.BibsNotToAddCaption = ItemsToAddBoxBibsNotToAddCaption;
    
    /**
     i18n Text that goes above the items that aren't going to be added table, 
     set this for internationalization
     @type String
    */
    this.ItemsNotToAddCaption = ItemsToAddBoxItemsNotToAddCaption;

}

/**
Link the javascript object to the div tag
@param id the id of the div tag
*/
ItemsToAddBox.prototype.init = function(id){
    this.BIBTYPE = "bibItemDisplay";
    this.ITEMTYPE ="itemItemDisplay" ;
    this.id =id;
    this.div = $(id);
    this.divBody = $(id + "Body");
    this.divButtons = $(id + "Buttons");
}

/**
Creates a table object
@param caption the text that will be displayed above the table
@returns and table object
*/
ItemsToAddBox.prototype.createTable = function(caption){
   var s = document.createElement("span");
   s.className = "portletItemHeaderText";
   s.innerHTML = caption;
   var div = document.createElement("div");
   div.style.height= "100px";
   div.style.overflow = "auto";
   div.style.border = "1px solid #dbdbdb";
   var tbl = document.createElement("table");
   tbl.setAttribute("width","100%");
   div.appendChild(tbl);
   this.divBody.insertBefore(s,this.divButtons);
   this.divBody.insertBefore(div,this.divButtons);
   return tbl
}

/**
Clears out the body div tag
*/
ItemsToAddBox.prototype.clearBody = function(){
  var childrenToRemove = new Array();
  for (var i=0;i<this.divBody.childNodes.length;i++){
    var c = this.divBody.childNodes[i];
    if(c.id != this.divButtons.id){
       childrenToRemove.push(c);
    }
  }

  for (var i=0;i<childrenToRemove.length;i++){
       this.divBody.removeChild(childrenToRemove[i]);
  }
}

/**
Addes all the items that are passed in to the table that is passed in
@param tbl  a table object to add
@param items items to too add to the table
@param itemType  specifies the item types that it passed in
*/
ItemsToAddBox.prototype.addToTable = function(tbl,items,itemType){
    for(var i=0;i<items.length;i++){
        var txt = $(itemType + items[i]).value;
        tbl.insertRow(i);
        tbl.rows[i].insertCell(0);
        tbl.rows[i].cells[0].innerHTML = txt;
    }
}

/**
This is the main function that gets used.  It will display the dialog box and create all the tables
for everything that is passed in.
@param menu a menu object that will be set and used
@param listId the listId for all the bibs and items passed in
@param bibsWillAdd  a list of bibs that will be added
@param itemsWillAdd a list of items that will be added
@param bibsNotAdd a list of bibs that will not be added
@param itemsNotAdd a list of items that will not be added
*/
ItemsToAddBox.prototype.addItems = function(menu,listId,bibsWillAdd,
                                             itemsWillAdd, bibsNotAdd, itemsNotAdd){
    this.listId = listId;
    this.bibsWillAdd = bibsWillAdd;
    this.itemsWillAdd = itemsWillAdd;
    this.menu = menu;
    this.clearBody();
    if (bibsWillAdd.length >0){
        tbl = this.createTable(this.BibsToAddCaption);
        this.addToTable(tbl,bibsWillAdd,this.BIBTYPE);
    }

    if (itemsWillAdd.length >0){
        tbl = this.createTable(this.ItemsToAddCaption);
        this.addToTable(tbl,itemsWillAdd,this.ITEMTYPE);
    }

    if (bibsNotAdd.length >0){
        tbl = this.createTable(this.BibsNotToAddCaption);
        this.addToTable(tbl,bibsNotAdd,this.BIBTYPE);
    }

    if (itemsNotAdd.length >0){
        tbl = this.createTable(this.ItemsNotToAddCaption);
        this.addToTable(tbl,itemsNotAdd,this.ITEMTYPE);
    }
}


/**
Makes the div array display.  Set the style property of the main div
*/
ItemsToAddBox.prototype.display = function(){
    this.div.style.visibility ="visible";
    this.div.style.block = "block";
}

/**
The method that gets called when the cancel button is pressed
*/
ItemsToAddBox.prototype.cancel = function(){
    this.hide();
    this.bibsWillAdd = new Array();
    this.itemsWillAdd = new Array();
}

/**
The method that gets called when the continue botton gets pressed
This method calls the addToMyList functoin
@see #addToMyList
*/
ItemsToAddBox.prototype.save = function(){
    var bibids = "";
    var itemids = "";
    for(var i=0;i<this.bibsWillAdd.length;i++){
      if(i==0){
         bibids = this.bibsWillAdd[i];
      }
      else{
         bibids = bibids + "," + this.bibsWillAdd[i];
      }
    }

    for(var i=0;i<this.itemsWillAdd.length;i++){
        if(i==0){
            itemids = this.itemsWillAdd[i];
        }
        else{
            itemids = itemids + "," + this.itemsWillAdd[i];
        }
    }

    if (bibids.length >0 || itemids.length > 0){
        addToMyList(this.menu,this.listId,bibids,itemids);
    }

    // clear
    this.menu = null;
    this.bibsWillAdd = new Array();
    this.itemsWillAdd = new Array();
    this.listid = "";
    this.hide();
}

/**
Hides the div 
*/
ItemsToAddBox.prototype.hide = function(){
    this.div.style.visibility = "hidden";
    this.div.style.block = "none";
}



/**
returns a reference to a function that will call the function passed in when executed.
It is used to get around some wierd javascript stuff
@param func function to be called later
*/
function ToolbarCalLater(obj,func,arg){
    /* Return a reference to an anonymous inner function created
       with a function expression:-
    */
    
    if(arguments.length ==3){
        var arg1 = arguments[2];
        var f = function(){                                                     
                  func.call(obj,arg1);                                                  
            };
    }
    else if(arguments.length ==4){  
      var arg1 = arguments[2];
      var arg2 = arguments[3];
      var f = function(){                                                     
                  func.call(obj,arg1,arg2);                                                
            };
    }    
    return (f)
}

AddToMenu.prototype = new MyListMenu;
AddToMenu.prototype.constructor = AddToMenu;

function AddToMenu(){
    MyListMenu.prototype.constructor.call(this);
}

/**
This function checks if nothing is selected and then calls superclass toggle()
which opens the menu if closed and closes if open.
*/
AddToMenu.prototype.toggle = function () {
    if (!this.isOpen){
        var bibIds = getSelectedInputs("bibID");
        var itemIds = getSelectedInputs("itemID");
        if (bibIds.length == 0 && itemIds.length ==0) {
           alert(ErrorNothingSelected);
           return true;
        }
    }

    //call the superclass function
    MyListMenu.prototype.toggle.call(this);
}

/**
Uses the data ref object passed in the init and adds the entries
to the menu and sets up links
*/
MyListMenu.prototype.updateMenu = function (){
    var menuForm =this.menuForm;
    this.clearForm();
    menuForm.innerHTML = this.AddToText;
    menuForm.appendChild(document.createElement("br"));
    var listItems = this.dataRef.get();
    for (var i=0;i<listItems.length;i++){
        var a = document.createElement("a");
        a.innerHTML = listItems[i]["name"];
        a.setAttribute("href","javascript:" + this.addToListFunc + "(" + this.name + "Menu,\'"  + listItems[i].id + "\')");
        menuForm.appendChild(a);
        var br = document.createElement("br");
        menuForm.appendChild(br);
    }

    menuForm.appendChild(document.createElement("br"));

    var d = document.createElement("div");
    d.setAttribute("id",this.name + "addInputArea");
    if(this.createListBoolean == true){

        var btn =   document.createElement("button");
        btn.className = "portletButton";
        btn.setAttribute("type","button");
        btn.innerHTML = this.CreateNewListText;
        btn.setAttribute("id","createNewListLink");
        btn.onclick = ToolbarCalLater(null,createNewList, this.name);
        d.appendChild(btn);
    }
    menuForm.appendChild(d);
    menuForm.appendChild(document.createElement("br"));
    menuForm.appendChild(document.createElement("br"));

    var btn = document.createElement("button");
    btn.className = "portletButton";
    btn.setAttribute("type","button");
    btn.innerHTML = this.CancelText;
    btn.setAttribute("id","cancelMyMenu");
    var obj =  eval(this.name + "Menu");
    var func = obj.toggle ;
    btn.onclick = ToolbarCalLater(obj,func,"");
    menuForm.appendChild(btn);

 }

/**
This function checks if nothing is selected and then calls superclass toggle()
which opens the menu if closed and closes if open.
*/
//MyListMenu.prototype.toggle = function () {
//    if (!this.isOpen){
//        var bibIds = getSelectedInputs("bibID");
//        if (bibIds.length == 0) {
//           alert(ErrorNothingSelected);
//           return true;
//        }
//    }
//
//    //call the superclass function
//    ToolbarMenu.prototype.toggle.call(this);
//}





/**
Function to create the input box and link that the user then can use to create a new list
@param name the name of the div that contains the input area
@return none
*/
function createNewList(name){
    var div = document.getElementById(name + "addInputArea");

    var childrenToRemove = new Array();
    for (var i=0;i<div.childNodes.length;i++){
    childrenToRemove.push(div.childNodes[i]);
    }

    for(var i=0;i<childrenToRemove.length;i++){
        div.removeChild(childrenToRemove[i]);
    }

    var t = document.createElement("input");
    t.setAttribute("type","text");
    t.setAttribute("id",name +"Text");
    t.setAttribute("size","18");

    t.style.margin = "0px 10px 0px 0px";
    t.style.padding= "0px 3px 0px 3px";

    t.value = DefaultCreateNewListText ;

    div.appendChild(t);
    t.focus();
    t.select();

    var btn = document.createElement("button");
    btn.setAttribute("type","button");
    btn.id = "createNewList";
    btn.className = "portletButton";
    btn.innerHTML = createNewListValue;
    btn.onclick = ToolbarCalLater(null,addNewList, eval(name + "Menu"),name + "Text");
    div.appendChild(btn);
}




/**
Completion handler that gets called after the HTTP Request comes back that adds
the new list. If no error the new list will be added to menu, and the menu will close.  If an error
occured (on the server) an alert box will pop up and display the variable ErrorAddingNewListText, you
can override the ErrorAddingNewListText for internationlization
@param data a JSON string that has at least an error attribute that is either
true or false
@return none
*/
function updateMyListCompletionHandler(data){
    try{
       var resultObj = eval('(' + data + ')');
    }
    catch(err){
       var resultObj = new Object();
       resultObj["error"] = true;
    }

    var error = resultObj['error'];
    if (error == true){
        alert(ErrorAddingNewListText);
    }
    else{
        var listId = resultObj['result']['id'];
        var bibIds = getSelectedInputsAsString("bibID");
        var itemIds = getSelectedInputsAsString("itemID");
        var itemIdsWithBibs = getSelectedItemsWithBibIds("itemIDbibID");
        var url = "/PassThrough/mylist";
        var menu = this.info["menu"];

        if(bibIds !== "" || itemIds != ""){
            addToMyList(menu,listId,bibIds,itemIds,itemIdsWithBibs,url);
        }

        myList.add(listId,resultObj['result']['name']);
        menu.updateMenu();
        menu.close();
    }
}

/**
Takes the string passed in of comma seperated values and returns an array
@param a string of comma seperated values
@return <array> an array of values
*/
function getArrayFromString(strObj){
     var strObj = new String(strObj);
     var rt = strObj.split(',');
     return rt
}



/**
The completion handler that gets called when the HTTP Request returns that adds to a list.  If an Error
occured, an alert box will pop up with the value of the variable ErrorAddingToList,
ErrorAddingToList can be overriden for internationlization.  If no error,
the menu closes and all the checkboxs that were checked are unchecked, and the
rows unhighlighted, also all the checkbox's attribute inmylist are updated to "true"
@param data a JSON string that has at least an error attribute that is either
true or false
*/
function addToMyListCompletionHandler(data){
    try{
       var resultObj = eval('(' + data + ')');
    }
    catch(err){
       var resultObj = new Object();
       resultObj["error"] = true;
    }
    if (resultObj["error"] == true){
        alert(ErrorAddingToList);
    }
    else{
        completeMyListAction(this);
    }
}

function addToTempListCompletionHandler(data){
    completeMyListAction(this)
}

function completeMyListAction(owner){
    //close the menu
    var menu = owner.info["menu"];
    menu.close();

    uncheckInputs("itemID");
    uncheckInputs("bibID");

    var bibIds = new Array();
    var itemIds = new Array();

    if(owner.info["bibIds"] != ""){
        bibIds = getArrayFromString(owner.info["bibIds"])
    }

    if(owner.info["itemIds"] != ""){
        itemIds = getArrayFromString(owner.info["itemIds"])
    }

   for(var i=0;i<bibIds.length;i++){
       var n = "bibID" + bibIds[i];
       var checkBox = $(n);
       checkBox.setAttribute("inMyList","true")
    }

    for(var i=0;i<itemIds.length;i++){
       var n = "itemID" + itemIds[i];
       var checkBox = $(n);
       checkBox.setAttribute("inMyList","true")
     }
}


var addToTempListURL;

/**
This function gets called when the user clicks on a list name in the my list menu, It takes
all the bib and items ids that were checked and addes them to the list. If no bibs are
items are checked, and alert box pops up. It first checks those bib and list ids to see
if they are already in a list, it does this my looking at the inmylist attribute of the check box.
If this isset it to true brings up a dialog that displays which bibs and ids
are going to be added or not.  It then makes an HTTP Request to add those bibs and
items to the listid passsed in.  The HTTP request then calls addToMyListCompletionHandler.
@see addToMyListCompletionHandler
@see ItemsToAddBox
@param menu the menu that is used (in this case the MyListMenu instance)
@param listId  the users list id that they want to add to
*/
function myListMainAddToMyList(menu,listId){
    var bibIds = getSelectedInputs("bibID");
    var itemIds = getSelectedInputs("itemID");
    var itemIdsWithBibs = getSelectedItemsWithBibIds("itemIDbibID");
    var url = "/PassThrough/mylist";

    if (bibIds.length >0 || itemIds.length>0){
        addToMyList(menu,listId,bibIds,itemIds,itemIdsWithBibs,url)
   }
   else{
        alert(ErrorNoBibsItemsSelected);
   }
}

/**
Find all checkboxes that start with the name passed in
@param name = name to look for inputs elements, it does a regular expression on the name
@param inputs, optional if supplied it will search through all the
input elements passed in, otherwise it will get all input elements
in the document
@return <array> array all values for all inputs that match that name and that are checked
*/
function getSelectedInputs(name,inputs)
{
    if (arguments.length>1){
        var inputs = inputs
    }
    else{
        var inputs = document.getElementsByTagName("input");
    }
    var values = new Array();
    var reName = new RegExp("^" + name + ".*");

    for(var i=0;i<inputs.length;i++)
    {
        // Collect all item ids
        if(reName.exec(inputs[i].name)){
            if (inputs[i].checked == true && inputs[i].style.visibility != "hidden"){
                values.push(inputs[i].value);
            }
        }
    }
    return values;
}

function getSelectedInputsRequestValues(name,inputs)
{
    if (arguments.length>1){
        var inputs = inputs
    }
    else{
        var inputs = document.getElementsByTagName("input");
    }
    var values = new Array();
    var reName = new RegExp("^" + name + ".*");

    for(var i=0;i<inputs.length;i++)
    {
        // Collect all item ids
        if(reName.exec(inputs[i].name)){
                values.push(inputs[i].value);
        }
    }
    return values;
}

/**
Find all checkboxes that start with the string passed in and append the end of the name to
the value returned.
@param name = name to look for inputs elements, it does a regular expression on the name

@return <array> array all values for all inputs that match that name and that are checked
*/
function getSelectedItemsWithBibIds(string){
    var inputs = document.getElementsByTagName("input");
    var values = new Array();
    var reName = new RegExp("^" + string + ".*");

    for(var i=0;i<inputs.length;i++)
    {
        // Collect all item ids
        var name = inputs[i].name;
        if(reName.exec(name)){
            if (inputs[i].checked == true && inputs[i].style.visibility != "hidden"){
                var v = inputs[i].value;
                v = v +':'+ name.substring(string.length, name.length)
                values.push(v);
            }
        }
    }
    return values;
}


/**
Find all checkboxes that start with the name passed in
name to look for inputs elements, it does a regular expression on the name
@param inputs, optional if supplied it will search through all the
input elements passed in, otherwise it will get all input elements
in the document
@return  <string> a comma seperated string all values for all inputs that match that name and that are checked
*/
function getSelectedInputsAsString(name,inputs){
    if (arguments.length>1){
        var inputs = inputs;
    }
    else{
        var inputs = document.getElementsByTagName("input");
    }
    var values = "";
    var reName = new RegExp("^" + name + ".*");

    for(var i=0;i<inputs.length;i++)
    {
        // Collect all item ids
        if(reName.exec(inputs[i].name))
        {
            if (inputs[i].checked == true && inputs[i].style.visibility != "hidden"){
                if (values ==""){
                    values = inputs[i].value;
                }
                else{getHttpObject()
                    values =  values + ","  + inputs[i].value ;
                }
            }
        }
    }
    return values;
}

/**
This function will uncheck all input boxes that match the name passed in,
and will unhighlight the row, if it is bib checkbox
@param name the name of the input boxes, uses a regular expression to
match the name.  It has to start with the name passed in
@param inputs, optional if passed in, it will use those inputs to loop through, it they
aren't passed in, it will get all inputs on the page
@return none
*/
function uncheckInputs(name,inputs){
    var boxCells = new Array();

    if (arguments.length>1){
        var inputs = inputs;
    }
    else{
        var inputs = document.getElementsByTagName("input");
    }
    var reName = new RegExp("^" + name + ".*");
    for(var i=0;i<inputs.length;i++){
        // Collect all item ids
        if(reName.exec(inputs[i].name)){
            if (inputs[i].checked == true){
                inputs[i].checked = false;
                var row = $("row_" + inputs[i].id);
                // Try to get the row
                if (row != null){
                   //If it has a row with that ID
                   // put in this array so we can unhighlight it
                   boxCells.push(row);
                }
            }
        }
    }

    if (boxCells.length > 0){
    	if (document.getElementById("selectAll") != null){
            document.getElementById("selectAll").checked = false;
        }
        summary.highlightBars(false, boxCells);
    }
}


/**
This function will http://www.cbronline.com/article_news.asp?guid=E23CEBF7-134A-460B-ACAD-050BBF8C632Amake the servlet call to add bibs and items passed in.  It creates a POST request.
@param menu the menu object that was used
@listId <integer> the listid for the list to add too
@bibIds <string> a string of comma seperated values of bib ids to add
@itemIds <string> a string of comma seperated values of item ids to add to the list
@return none
*/
function addToMyList(menu,listId,bibIds,itemIds,itemIdsWithBibs,url){
    if (addToMyListProblems)
    {
        alert(ErrorPageHasProblemRecords);
    }
    if (bibIds != "" && !bibMyListAllowed)
    {
        alert(ErrorBibMyListNotAllowed);
    }
    else if (itemIds != "" && !itemMyListAllowed)
    {
        alert(ErrorItemMyListNotAllowed);
    }
    else if (bibIds != "" || itemIds != "")
    {
        var action = "addToMyList";
        var postData = new PostData();
        postData.append("action", action);
        postData.append("myListUserListId", listId);
        postData.append("bibIds", bibIds);
        postData.append("itemIds", itemIds);
        if (itemIdsWithBibs != "")
        {
            postData.append("itemIdsWithBibs", itemIdsWithBibs);
        }
        var reqObj = getHttpObject();
        reqObj.info = {"bibIds":bibIds,"itemIds":itemIds,"menu":menu,"itemIdsWithBibs":itemIdsWithBibs};
        reqObj.open("POST", url, true);
        reqObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        if (listId == tempListId){
            reqObj.completionHandler = addToTempListCompletionHandler;
        }
        else{
            reqObj.completionHandler = addToMyListCompletionHandler;
        }
        reqObj.send(postData.get());
    }
}

/**
Makes the servlet call to create a new list.  It will make the call if the name is not "", does not match an existing
list, and if it does not equal the same value as in DefaultCreateNewListText. DefaultCreateNewListText
is to be used for internationalization
@param <object> menu object where this is being called from
@param <string> the id of the text box where the new name is
*/
function addNewList(menu,textBoxName){

    var textBox = $(textBoxName);
    var newListItem = textBox.value;
    var listExists = false;
    for (var i = 0; i < menu.dataRef.myList.length; i++){
        if (menu.dataRef.myList[i].name == newListItem){
            listExists = true;
            break;
        }
    }

    if (listExists == true){
        alert(ErrorListAlreadyExists);
    }

    if(newListItem != DefaultCreateNewListText && newListItem != "" && !listExists){
        var postData = new PostData();
        postData.append("action","createNewMyList");
        newListItem = encodeURI(newListItem, "utf-8");
        postData.append("newListName", newListItem);
        //var url = "/uPortal/PassThrough/mylist";
        var url = "/PassThrough/mylist";
        var reqObj = getHttpObject();
        reqObj.open("POST",url,true);
        reqObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        reqObj.completionHandler = updateMyListCompletionHandler;
        reqObj.info = {"menu":menu};
        reqObj.send(postData.get());
    }
    else{
        textBox.focus();
        textBox.select();
    }

}




/**
collects all the bibs and items that are checked and submits the form to remove from the
current list
*/
function removeFromMyList(){
    selectedBibIds = getSelectedInputs("bibID");
    selectedItemIds = getSelectedInputs("itemID");
    if (selectedBibIds != "" || selectedItemIds != ""){
        document.removeForm.bibIds.value = selectedBibIds;
        document.removeForm.itemIds.value = selectedItemIds;
        document.removeForm.submit();
    }
    else{
        alert(ErrorNothingSelected);
    }

}

function constructArray()
{
    var values = new Array( arguments.length);
    for( var i = 0; i < arguments.length; i++)
    {
        values[ i] = arguments[ i];
    }

    return values;
}

/**
if you are not a guest, collects all bibs and items checked and
calls the targetURL with the bibs and items in the query string
@param targetUrl the url to call
*/
function request(ev, targetUrl, batchRequestsAllowed, bibRequestsAllowed, itemRequestsAllowed, forwardItemLinks, bibIds, itemIds)
{
    if(authenticated == false)
    {
        if (confirm(loginPrompt))
        {
            Login();
        }
    }
    else
    {
        var selectedBibIds = bibIds;
        if (selectedBibIds == null)
        {
            selectedBibIds = getSelectedInputs("bibID");
        }
        var requestableBibIds = getSelectedInputsRequestValues("reqBibID");
		for (var i=0; i < selectedBibIds.length; i++)
		{
            var f = false;
            for (var j=0; j < requestableBibIds.length; j++)
            {
            	if (selectedBibIds[i] == requestableBibIds[j])
           		{
           		   f = true;
           		   break;
           		}
            }
            
           	if (f == false)
           	{
               alert(ErrorOneOrAllItemsRequestsNotAllowed);
           	   return;
           	}
		}
        
        
        var selectedItemIds = itemIds;
        if (selectedItemIds == null)
        {
            selectedItemIds = getSelectedInputs("itemID");
        }
        var requestableItemIds = getSelectedInputsRequestValues("reqItemID");
		for (var i=0; i < selectedItemIds.length; i++)
		{
            var f = false;
            for (var j=0; j < requestableItemIds.length; j++)
            {
            	if (selectedItemIds[i] == requestableItemIds[j])
           		{
           		   f = true;
           		   break;
           		}
            }
            
           	if (f == false)
           	{
               alert(ErrorOneOrAllItemsRequestsNotAllowed);
           	   return;
           	}
		}
		
        if (!batchRequestsAllowed && (selectedBibIds.length > 1 || selectedItemIds.length > 1))
        {
            alert(ErrorBatchRequestsNotAllowed);
        }
        else if (selectedBibIds != "" && !bibRequestsAllowed)
        {
            alert(ErrorBibRequestsNotAllowed);
        }
        else if (selectedItemIds != "" && !itemRequestsAllowed)
        {
            alert(ErrorItemRequestsNotAllowed);
        }
        else if (selectedBibIds != "" || selectedItemIds != "")
        {
            url = targetUrl
                    .replace("=--bibIds--", "=" + selectedBibIds)
                    .replace("=--itemIds--", "=" + selectedItemIds)
                    .replace("=--requestForwardItemLinks--", "=" + forwardItemLinks);
            window.location = url;
        }
        else
        {
            alert(ErrorNothingSelected);
        }
    }
}



/**
This is the function that gets called when the ajax call is finished for the email servlet
@param data string, json string that has a an error key
*/
function emailCompletionHandler(data){
    try{
       var resultObj = eval('(' + data + ')');
    }
    catch(err){
       var resultObj = new Object();
       resultObj["error"] = true;
    }

    if (resultObj["error"] == true){
        alert(ErrorSendingEmail);
    }
}

EmailMenu.prototype= new Menu();
EmailMenu.constructor = EmailMenu;

function EmailMenu(){
    Menu.prototype.constructor.call(this);
}

/**
This function checks if nothing is selected and then calls superclass toggle()
which opens the menu if closed and closes if open.
*/
EmailMenu.prototype.toggle = function () {
    if (!this.isOpen){
        var bibIds = getSelectedInputs("bibID");
        var itemIds = getSelectedInputs("itemID");

        if (bibIds.length == 0) {
            if (itemIds.length > 0){
                alert(ErrorCannotEmailItems);
            }
            else{
                alert(ErrorNothingSelected);
            }
           return true;
        }
    }

    //call the superclass function
    Menu.prototype.toggle.call(this);
}

/**
using ajax, calls the email servlet, checks to make sure,
that the email address being sent to looks like a valid email address
Will send a request to the servlet, the bibs and items selected, along with the
To, Subject, Format from the menu, sets the completion handler
to be the function emailCompletionHandler
*/
function sendEmail(menuName,locale,isRTL){
   // close email dialog
   var m =  eval(menuName + "Menu");
   m.toggle();
   
   var to = $(menuName + "To").value;
   //validate the email address
   if (!validEmail(to)){
        alert(ErrorInvalidEmailAdressTo);
        var input =   $(menuName + "To");
        input.focus()
        input.select();
        return true
   }

   var subject = $(menuName + "Subject").value;
   var format = "html";
   var formatRadio = $(menuName + "Format");
   if ( formatRadio.checked == true){
       format = formatRadio.value;
   }

   var bibIds = getSelectedInputs("bibID");
   var itemIds = getSelectedInputs("itemID");
   if (bibIds.length == 0) {
       if (itemIds.length > 0){
           alert(ErrorCannotEmailItems);
       }
       else{
           alert(ErrorNothingSelected);
       }
       emailMenu.toggle();
       return true;
   }

   var action = "sendEmail";

   var postData = new PostData()
   postData.append("action",action);
   postData.append("To",encodeURI(to, "utf-8"));
   postData.append("Subject",encodeURI(subject, "utf-8"));
   postData.append("Format",format);
   postData.append("bibIds",bibIds);
   postData.append("itemIds",itemIds);
   postData.append("locale",locale);
   postData.append("isRTL",isRTL);

   //var url = "/uPortal/PassThrough/mylist";
   var url = "/PassThrough/mylist";

   var reqObj = getHttpObject();
   reqObj.open("POST",url,true);
   reqObj.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
   reqObj.completionHandler = emailCompletionHandler;
   reqObj.send(postData.get());
}


/**
This is the function that gets called when the ajax call is finished for the alert servlet
@param data string, json string that has a an error key
*/
function alertCompletionHandler(data)
{
    try
    {
        var resultObj = eval('(' + data + ')');
    }
    catch(err)
    {
        var resultObj = new Object();
        resultObj["error"] = true;
    }

    if (resultObj["error"] == true)
    {
        alert(ErrorAddingAlerts);
    }
    else
    {
        alert(SuccessAddingAlerts);
    }
}

/**
using ajax, calls the alert servlet
Will send a request to the servlet, the bibs and items selected, along with the
alert type, sets the completion handler
to be the function alertCompletionHandler
*/
function addAlerts(ev, isAuthor, isSeries, isSubject)
{
    if (authenticated == false)
    {
        if (confirm(loginPrompt))
        {
            loginMenu.action = request;
            var args = [null,ev,targetUrl]
            loginMenu.args = args;
            loginMenu.open();
            loginMenu.setFocus();
            if (ev)
            {
                if (ev.stopPropagation)
                {
                    ev.stopPropagation();
                }
                else
                {
                    ev.cancelBubble = true;
                }
            }
        }
    }
    else
    {
        var links = getSelectedInputs("bibID");
        if (links.length == 0)
        {
            alert(ErrorNothingSelected);
            return true;
        }
        var action = "addAlerts";

        var postData = new PostData()
        postData.append("action", action);
        postData.append("links", links);
        postData.append("isAuthor", isAuthor);
        postData.append("isSeries", isSeries);
        postData.append("isSubject", isSubject);

        //var url = "/uPortal/PassThrough/alert";
        var url = "/liferay/PassThrough/alert";

        var reqObj = getHttpObject();
        reqObj.open("POST", url, true);
        reqObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        reqObj.completionHandler = alertCompletionHandler;
        reqObj.send(postData.get());
    }
}

function printout() {
    var bibIds = getSelectedInputs("bibID");
    var itemIds = getSelectedInputs("itemID");

    if (bibIds.length == 0 && itemIds.length == 0) {
       alert(ErrorNothingSelected);
       return true;
    }

    window.print();
}

