//include AFTER presentation.js
var MySelectionsServicePageName = "modify.my.selections";
var MySelectionsExportFormatPageName = "export.format";

function modifyMySelections(action, uri, async)
{
	new Ajax.Request(location.pathname + "/" + MySelectionsServicePageName, {parameters:{'list.action':action, 'list.value':uri}});
	//new Ajax.Request(location.pathname + "/" + MySelectionsServicePageName, {parameters:{'list.action':action, 'list.value':encodeURIComponent(uri)}});
}

function toggleMySelectionsWithCheckbox(url, shouldAppend)
{
	if(shouldAppend)
		modifyMySelections('Add', url, true);
	else
		modifyMySelections('Remove', url, true);
}

function toggleMySelections(url, button)
{
	toggleMySelectionsWithCheckbox(url,button.className != "remove");
	if(button.className == "remove")
	{
		button.className = "add";
		button.title = "Add this document to My Selections";
		button.childNodes[0].nodeValue = "Add to My Selections";
	}
	else
	{
		button.className = "remove";
		button.title = "Remove this document from My Selections";
		button.childNodes[0].nodeValue = "Remove from My Selections";
	}
}

function removeCheckedItems(formEl)
{
	if (formEl == null)	return;
	
	formEl.action = location.pathname+"/"+MySelectionsServicePageName;
	formEl.submit();	
}

function compileCheckedItems(formEl)
{
	if (formEl == null)	
		return;
	
	// If No MySelections Selected - Error!
	if (($(MySelectionsFormId) != null) && (areAnyMySelectionsChecked() == false))
	{
		alert("No items have been selected for Export!");
		return;
	}

	formEl.submit();
}

// Export button pressed (this event handler is set up in presentation.js)
function exportCheckedItems(formEl)
{
	if (formEl == null)	return;

	// Submit the page to the export service.
	formEl.action = MySelectionsExportFormatPageName;
	formEl.submit();
}

// Select/Deselect All MySelections Documents!
function updateMySelectionsCheckedItems(formEl, state)
{
  if (state)
    var action = "AddAll"       // Select All
  else
    var action = "RemoveAll";   // Deselect All

	// Getting Form Elements implemented dsifferently for Single and multiple Items!
	if (formEl[MySelectionsCheckboxName].length == null)
		// for Single
		var checkboxArray = new Array (formEl[MySelectionsCheckboxName]); // Add the Form Checkbox into a new Array.
	else
		// for multiple
		var checkboxArray = formEl[MySelectionsCheckboxName]; // Add all Form Checkboxes into the Array.

  var checkboxURLs = new Array(checkboxArray.length);   // The URL's - 1 for each Document Checkbox.
	for (var i = 0; i < checkboxArray.length; i++)
  {
		checkboxArray[i].checked = state; // Check/Uncheck the Checkbox.
    checkboxURLs[i] = escape(checkboxArray[i].value); // Capture and Encode the URL from the Checkbox.
	}

	new Ajax.Request(ApplicationPath+'/'+SessionDictionaryManagerPageName+'?session-key='+MySelectionsCheckItemsPostKey, {parameters:{'list.action':action, 'list.value':checkboxURLs.join()}});
}

// Select/Deselect Specific-Single MySelections Document!
function updateMySelectionsCheckedItem(mySelectionsURL, checkedState)
{
	var encodedUrl = escape(mySelectionsURL);
 	if (checkedState)
		addRemoveSessionDictionaryListValue(MySelectionsCheckItemsPostKey, 'Add', encodedUrl)
 	else
		addRemoveSessionDictionaryListValue(MySelectionsCheckItemsPostKey, 'Remove', encodedUrl)
}

// Post Selection/Deselection of MySelections Document!
function addRemoveSessionDictionaryListValue(key, action, checkboxURL)
{
	new Ajax.Request(ApplicationPath+'/'+SessionDictionaryManagerPageName+'?session-key='+key, {parameters:{'list.action':action, 'list.value':checkboxURL}});
}

// Check if any of the MySelections CheckBoxes are Checked?
function areAnyMySelectionsChecked()
{
	// Pre-Check Required Form is Available...
	if ($(MySelectionsFormId) == null)
		return false; // No form - No MySelections Checked!

 	// Capture EndPoints from MySelections Form - Look for Any MySelections Checked...
 	var elementList = $(MySelectionsFormId).select("[name='MySelectionsSelectedItems']");
	if (elementList.length > 0)
	{
		// Check the EndPoint Selections for Checked Status (ie. Checked True/False).
		for(i=0;i<elementList.length;i++) 
		{
			if (elementList[i].checked) // EndPoint Selection - Checked ?
				return true; // 1+ Items Checked!
		}
	}
	return false; // Processed All Items "0" Items Checked!!!
}

function areAllChecked(formEl, val)
{
	var checkboxArray = document.getElementsByName("ShowInlineSetting");
	if (checkboxArray.length == 0)
		return true;
	for (var i = 0; i < checkboxArray.length; i++)
	{
		//skip if not checked item or if not relevant to value
		if(checkboxArray[i].parentNode.parentNode.previousSibling.previousSibling.checked == false || checkboxArray[i].value.indexOf(val) != 0)
			continue;
		//found one that wasn't checked!
		if(checkboxArray[i].checked == false)
			return false;
	}
	//went through all of them and didn't find any unchecked
	return true;
}

// Select/Deselect Multiple item Checkbox's ("Additional Content"/"Related Content")
function toggleAdditionalContent(formEl,val)
{
	if(areAllChecked(formEl,val))
        new Ajax.Request(location.pathname + "/" + MySelectionsServicePageName, {parameters:{'my-selections-additional-content-exclude':val}});
	else
        new Ajax.Request(location.pathname + "/" + MySelectionsServicePageName, {parameters:{'my-selections-additional-content-include':val}});

        // Force Form Reload - Display the Updated Selections.
        location.reload(true);	
}

// Select/Deselect a Specific-Single Item Checkbox ("Additional Content"/"Related Content")
function toggleAdditionalContentItem(checkBoxEl)
{
	var mySelectionsForm = document.getElementById(MySelectionsFormId);

	if (checkBoxEl.checked)
        new Ajax.Request(location.pathname + "/" + MySelectionsServicePageName, {parameters:{'my-selections-additional-content-include':checkBoxEl.value}});
	else
        new Ajax.Request(location.pathname + "/" + MySelectionsServicePageName, {parameters:{'my-selections-additional-content-exclude':checkBoxEl.value}});
}

                                                                 
// Check the selections for any non modus (ie SiteDirector) content.
// This method is only relevant when a user has choosen the Export To Word
// feature via the My Selections Page. This method assumes that items
// have been selected (ie the check was performed by another method).
function validRTFSelection()
{    
    //If this element does not exist then the request must not have come
    //from the My Selections page.
    if ($(MySelectionsFormId) == null)
        return true; 
   
    // Capture EndPoints from MySelections Form - Look for Any MySelections Checked...
    var elementList = $(MySelectionsFormId).select("[name='MySelectionsSelectedItems']");
    var non_modus_counter = 0;
    var selections_counter = 0;
    if (elementList.length > 0)
    {
        // Check the EndPoint Selections for Checked Status (ie. Checked True/False).
        for(i=0;i<elementList.length;i++) 
        {
            if (elementList[i].checked) // EndPoint Selection - Checked ?
            {
                var uri = elementList[i].value.split('?');
                if( uri.length > 1 )
                {
                    if(uri[0].indexOf('$') > 0 )
                    {
                      non_modus_counter = non_modus_counter + 1;
                    }
                }
                selections_counter = selections_counter + 1;
            }
        }
    }
    //if( non_modus_counter == selections_counter )
    //{
    //    alert("Your selection only contains documents that are not supported by the 'Export as Word' option.\nThe Export has been terminated." );
    //    return false;
    //}
    //if( non_modus_counter > 0 )
    //{
    //    alert("You have selected documents that are not supported by the 'Export as Word' option.\nThese documents will be ignored." );
    //}
    //if( non_modus_counter == 0 )
    //  alert("Selection contain all modus documents" );	
    if( non_modus_counter > 0 )
    {
        answer = confirm("*** Warning ***\nYour selection contains documents from Databases which are not supported by the\nBrookers Online Export function. Formatting from these documents will not be\nretained in your export. Export is only supported in Databases on the\nnew Brookers Online platform (those indicated by a starburst icon on the\nDatabases page).\n\nDo you want to continue?");
        return answer;            
    }
    return true; // Ok to continue the export...
}
