//Author				: Kobus du Toit
//Date Created			: 11-Apr-2006
//Last Changed by		: Kobus du Toit
//Date Changed			: 18-Aug-2006
//Version				: 2.0.18082006
//Comments:
//Date:		Desc:															
//--------------------------------------------------------------------------------------------
//11-Apr-2006	Shuffler App reborn and combined into one Page
//07-Jun-2006	Altered the filtering to avoid duplicates
// *******************************************************************************************
//27-Jul-2006	For the Shuffler filtering to work correctly in the framework, you NEED to put 
//				the function "ClearShufflerObjects()" in the Component_Preload_JS Field of the 
//				component/page which you are loading in the components table
// *******************************************************************************************
//18-Aug-2006	Optimized the way the items were moved across the boxes
//				Fixed a bug encountered when moving all the items from the one box to the 
//				other one, and back

//ToDoList:
//Date:		Desc:															Status:
//--------------------------------------------------------------------------------------------
var MainBoxFilter;

function MoveItemsToFromBox(LeftBox, RightBox, allItems, LeftToRight) // LeftToRight boolean - true = move items from leftbox 2 rightbox
{

	var i = 0;
	var I = 0;
	var FoundTheElement = false;
	var lastElement = 0;

	if (LeftToRight == true) // HANDLE FROM LEFT TO RIGHT
	{
		// Check if the Mainbox object exists - If not, create both "copy" arrays
		if(!MainBoxFilter)
		{
			MainBoxFilter = new filterlist(LeftBox, RightBox) // Object initiated
		}

		if (allItems) // Send all the Items to the RightBox AND UPDATE BOTH THE COPY ARRAYS
		{

			for (i = 0; i < LeftBox.options.length; i++)
			{
				//alert(LeftBox.options.length);
				
				// Add the option to the right select box BEGIN
				var oOption = document.createElement("OPTION");
				oOption.text = LeftBox.options[i].text;
				oOption.value = LeftBox.options[i].value;
				RightBox.options.add(oOption);
				// Add the option to the right select box END
				
				// Add the option to the right Array BEGIN
				lastElement = MainBoxFilter.rightOptionsCopy.length;
				MainBoxFilter.rightOptionsCopy[lastElement] = new Option();
				MainBoxFilter.rightOptionsCopy[lastElement].text = oOption.text;
				MainBoxFilter.rightOptionsCopy[lastElement].value = oOption.value;
				// Add the option to the right Array END

				// Remove the item from the options array BEGIN
				FoundTheElement = false;
				for (I=0; I < MainBoxFilter.leftOptionsCopy.length && FoundTheElement == false; I++)
				{
					if (MainBoxFilter.leftOptionsCopy[I].value == oOption.value && MainBoxFilter.leftOptionsCopy[I].text == oOption.text)
					{
						FoundTheElement = true;
						MainBoxFilter.leftOptionsCopy.splice(I,1);
					}
				}
				// Remove the item from the options array END

				// Remove the item from the left select box BEGIN
					oOption = null;
				// Remove the item from the left select box END
				
			}
			
			document.getElementById('leftfilter').value = '';
			LeftBox.innerHTML = "";
			MainBoxFilter.set('',LeftBox, RightBox, true);
			SortListBox(RightBox);
		}
		else // Send Individual items over to the RightBox AND UPDATE BOTH THE COPY ARRAYS
		{
			var deleteCount = 0;
			var loopLength = LeftBox.options.length
			for (var i = 0; i < loopLength; i++)
			{
				if (LeftBox.options[i - deleteCount]) {
					if (LeftBox.options[i - deleteCount].selected)
					{
						// Add the option to the right select box BEGIN
						var oOption = document.createElement("OPTION");
						oOption.text = LeftBox.options[i - deleteCount].text;
						oOption.value = LeftBox.options[i - deleteCount].value;
						RightBox.options.add(oOption);
						// Add the option to the right select box END
						
						// Add the option to the right Array BEGIN
						var lastElement = MainBoxFilter.rightOptionsCopy.length;
						MainBoxFilter.rightOptionsCopy[lastElement] = new Option();
						MainBoxFilter.rightOptionsCopy[lastElement].text = oOption.text;
						MainBoxFilter.rightOptionsCopy[lastElement].value = oOption.value;
						// Add the option to the right Array END
						
						
						// Remove the item from the options array BEGIN
						FoundTheElement = false;
						for (I=0; I < MainBoxFilter.leftOptionsCopy.length && FoundTheElement == false; I++)
						{
							if (MainBoxFilter.leftOptionsCopy[I].value == oOption.value && MainBoxFilter.leftOptionsCopy[I].text == oOption.text)
							{
								FoundTheElement = true;
								MainBoxFilter.leftOptionsCopy.splice(I,1);
							}
						}
						// Remove the item from the options array END

						LeftBox.options[i - deleteCount] = null;
						deleteCount++;
					}
				}
				oOption = null;
			}
			SortListBox(RightBox);
			SortListBox(LeftBox);
		}
	}
	else // HANDLE "FROM RIGHT TO LEFT"
	{
		// Check if the Mainbox object exists - If not, create both "copy" arrays
		if(!MainBoxFilter) 
		{ 
			MainBoxFilter = new filterlist(LeftBox, RightBox) // Object initiated
		}
		
		if (allItems) // Send all the Items to the LeftBox AND UPDATE BOTH THE COPY ARRAYS
		{
			for (i = 0; i < RightBox.options.length; i++)
			{
			
				// Add the option to the Left select box BEGIN
				var oOption = document.createElement("OPTION");
				oOption.text = RightBox.options[i].text;
				oOption.value = RightBox.options[i].value;
				LeftBox.options.add(oOption);
				// Add the option to the Left select box END
				
				// Add the option to the Left Array BEGIN
				lastElement = MainBoxFilter.leftOptionsCopy.length;
				MainBoxFilter.leftOptionsCopy[lastElement] = new Option();
				MainBoxFilter.leftOptionsCopy[lastElement].text = oOption.text;
				MainBoxFilter.leftOptionsCopy[lastElement].value = oOption.value;
				// Add the option to the Left Array END

				// Remove the item from the right options array BEGIN
				FoundTheElement = false;
				for (I=0; I < MainBoxFilter.rightOptionsCopy.length && FoundTheElement == false; I++)
				{
					if (MainBoxFilter.rightOptionsCopy[I].value == oOption.value && MainBoxFilter.rightOptionsCopy[I].text == oOption.text)
					{
						FoundTheElement = true;
						MainBoxFilter.rightOptionsCopy.splice(I,1);
					}
				}
				// Remove the item from the right options array END
					
				oOption = null;
				
			}
			document.getElementById('rightfilter').value = '';
			RightBox.innerHTML = "";
			MainBoxFilter.set('',LeftBox, RightBox, false);
			SortListBox(LeftBox);
		}
		else // Send Individual items over to the LeftBox AND UPDATE BOTH THE COPY ARRAYS
		{
			var deleteCount = 0;
			var loopLength = RightBox.options.length
			for (var i = 0; i < loopLength; i++)
			{
				if (RightBox.options[i - deleteCount]) {
					if (RightBox.options[i - deleteCount].selected)
					{
						var oOption = document.createElement("OPTION");
						oOption.text = RightBox.options[i - deleteCount].text;
						oOption.value = RightBox.options[i - deleteCount].value;
						LeftBox.options.add(oOption);

						// add the element to the leftOptionsCopy array
						var lastElement = MainBoxFilter.leftOptionsCopy.length;
						MainBoxFilter.leftOptionsCopy[lastElement] = new Option();
						MainBoxFilter.leftOptionsCopy[lastElement].text = oOption.text;
						MainBoxFilter.leftOptionsCopy[lastElement].value = oOption.value;
						
						// Remove the item from the right options array BEGIN
						FoundTheElement = false;
						for (I=0; I < MainBoxFilter.rightOptionsCopy.length && FoundTheElement == false; I++)
						{
							if (MainBoxFilter.rightOptionsCopy[I].value == oOption.value && MainBoxFilter.rightOptionsCopy[I].text == oOption.text)
							{
								FoundTheElement = true;
								MainBoxFilter.rightOptionsCopy.splice(I,1);
							}
						}
						// Remove the item from the right options array END
						
						RightBox.options[i - deleteCount] = null;
						deleteCount++;
					}
				}
				oOption = null;
			}
			SortListBox(LeftBox);
			SortListBox(RightBox);
		}
	}
}

function MoveItemsToDB(FormName, submitToPage, MainID, proc2Save)
{
		var ShuffleCheckError = function(oXML) 
		{
			var returnVal = oXML.responseText
			regularCursor();
			if (returnVal.substr(0,5) == "ERROR") {
				alert(returnVal)
			}
			else {
				//alert(returnVal);
				alert("Item link successful");
			}
		}
		//alert(eval(FormName));
		
		var page = submitToPage //get form action
		
		var dataToSend = "action=ShuffleLinks&SubmitMe=true&MainID=" + MainID + "&proc2Save=" + proc2Save + "&" + fetchFormAndListboxData(FormName)
		//alert(fetchInputFormData(FormName));
		hiddenSubmit(page,dataToSend, ShuffleCheckError, 0, null, false)
}

function SortListBox(ListBox)
{
	var listboxItems = new Array();

	for (i = 0; i < ListBox.options.length; i++)
	{
		var listboxItemToAdd = ListBox.options[i].text + "^|^" + ListBox.options[i].value.toString();
		listboxItems[i] = listboxItemToAdd;
	}

	ListBox.innerHTML = "";
	listboxItems.sort(function (x,y){
			var a = String(x).toUpperCase();
			var b = String(y).toUpperCase();
			
			if (a >	b)
				return 1
		
			if (a < b)
				return -1
			return 0;
		});

	for (i = 0; i < listboxItems.length; i++)
	{
		var myNewItemandValue = new Array();
		myNewItemandValue = listboxItems[i].split("^|^");
		var textVal = myNewItemandValue[0,0];
		var IDVal = myNewItemandValue[1,1];
		
		var oOption = new Option(textVal,IDVal);
		ListBox.options.add(oOption);
	}
}


function filterlist(leftSelectBox, rightSelectBox)
{

  //==================================================
  // PARAMETERS
  //==================================================

  // HTML SELECT object
  // For example, set this to document.myform.myselect

  	this.leftSelectBox = leftSelectBox;
	this.rightSelectBox = rightSelectBox;
	
  // Flags for regexp matching.
  // "i" = ignore case; "" = do not ignore case
  // You can use the set_ignore_case() method to set this
  this.flags = 'i';
  
  // Which parts of the select list do you want to match?
  this.match_text = true;
  this.match_value = false;

  // You can set the hook variable to a function that
  // is called whenever the select list is filtered.
  // For example:
  // myfilterlist.hook = function() { }

  // Flag for debug alerts
  // Set to true if you are having problems.
  this.show_debug = false;
  
  //==================================================
  // METHODS 
  //==================================================

  //--------------------------------------------------
 	
   	this.init = function() 
	{
		// This method initilizes the object.
		// This method is called automatically when you create the object.

		if (!this.leftSelectBox) return this.debug('leftSelectBox not defined');
		if (!this.rightSelectBox) return this.debug('rightSelectBox not defined');

		// Make 2 "copy arrays" of BOTH the selection lists in order to have a copy of the ORIGINAL values.
		// These arrays will be modified when the items are moved to keep them in sync with the display.
		
		// LEFT BOX
		this.leftOptionsCopy = new Array();
		if (this.leftSelectBox && this.leftSelectBox.options) 
		{
			for (var i=0; i < this.leftSelectBox.options.length; i++) 
			{
				// Create a new Option
				this.leftOptionsCopy[i] = new Option();

				// Set the text for the Option
				this.leftOptionsCopy[i].text = leftSelectBox.options[i].text;

				// Set the value for the Option.
				// If the value wasn't set in the original select list,
				// then use the text.
				if (leftSelectBox.options[i].value) 
				{
					this.leftOptionsCopy[i].value = leftSelectBox.options[i].value;
				} 
				else 
				{
					this.leftOptionsCopy[i].value = leftSelectBox.options[i].text;
				}
			}
		}

		// RIGHT BOX
		this.rightOptionsCopy = new Array();
		if (this.rightSelectBox && this.rightSelectBox.options)
		{
			for (var i=0; i < this.rightSelectBox.options.length; i++) 
			{
				// Create a new Option
				this.rightOptionsCopy[i] = new Option();

				// Set the text for the Option
				this.rightOptionsCopy[i].text = rightSelectBox.options[i].text;

				// Set the value for the Option.
				// If the value wasn't set in the original select list,
				// then use the text.
				if (rightSelectBox.options[i].value)
				{
					this.rightOptionsCopy[i].value = rightSelectBox.options[i].value;
				}
				else
				{
					this.rightOptionsCopy[i].value = rightSelectBox.options[i].text;
				}
			}
		}
	}

  //--------------------------------------------------
  this.reset = function()
  {
    // This method resets the select list to the original state.
    // It also unselects all of the options.

    //this.set('');
    this.set('',this.leftSelectBox,this.rightSelectBox,true);
  }

  //--------------------------------------------------
  
  this.set = function(pattern, leftSelectBox, rightSelectBox, isLeft)
  {
    // This method removes all of the options from the select list,
    // then adds only the options that match the pattern regexp.
    // It also unselects all of the options.
		
	if (isLeft == true) { // Handle LEFT Selection box
		
		var loop=0, index=0, regexp, e;

		if (!this.leftSelectBox) return this.debug('leftSelectBox not defined');
		if (!this.leftSelectBox.options) return this.debug('leftSelectBox.options not defined');

		// Clear the select list so nothing is displayed
		this.leftSelectBox.options.length = 0;
		
		// Set up the regular expression.
		// If there is an error in the regexp,
		// then return without selecting any items.
		try 
		{
			// Initialize the regexp
			regexp = new RegExp(pattern, this.flags);
		} 
		catch(e) 
		{
			// There was an error creating the regexp.

			// If the user specified a function hook,
			// call it now, then return
			if (typeof this.hook == 'function') 
			{
				this.hook();
			}

			return;
		}

		// Loop through the entire LeftBox Array and
		// add the matching items to the LeftBox selectionlist
				
		//this.leftSelectBox.innerHTML = "";
				
		for (loop=0; loop < this.leftOptionsCopy.length; loop++) 
		{
			// This is the option that we're currently testing
			var option = this.leftOptionsCopy[loop];

			// Check if we have a match
			if ((this.match_text && regexp.test(option.text)) ||
				(this.match_value && regexp.test(option.value))) 
			{
				this.leftSelectBox.options[index++] = new Option(option.text, option.value, false);
			}
		}

		// Sort the Left box once the for-loop completed
		SortListBox(leftSelectBox);

		// If the user specified a function hook,
		// call it now
		if (typeof this.hook == 'function') 
		{
			this.hook();
		}
	}
	else { // Handle RIGHT
		
		var loop=0, index=0, regexp, e;

		if (!this.rightSelectBox) return this.debug('rightSelectBox not defined');
		if (!this.rightSelectBox.options) return this.debug('rightSelectBox.options not defined');

		// Clear the select list so nothing is displayed
		this.rightSelectBox.options.length = 0;

		// Set up the regular expression.
		// If there is an error in the regexp,
		// then return without selecting any items.
		try 
		{

		// Initialize the regexp
		regexp = new RegExp(pattern, this.flags);

		} 
		catch(e) 
		{
			// There was an error creating the regexp.

			// If the user specified a function hook,
			// call it now, then return
			if (typeof this.hook == 'function') 
			{
				this.hook();
			}

			return;
		}

		// Loop through the entire RightBox Array and
		// add the matching items to the RightBox selectionlist
		for (loop=0; loop < this.rightOptionsCopy.length; loop++) 
		{
			// This is the option that we're currently testing
			var option = this.rightOptionsCopy[loop];

			// Check if we have a match
			if ((this.match_text && regexp.test(option.text)) ||
				(this.match_value && regexp.test(option.value))) 
			{
				this.rightSelectBox.options[index++] = new Option(option.text, option.value, false);
			}
		}

		// Sort the RightBox once the for-loop completed
		SortListBox(rightSelectBox);
		
		// If the user specified a function hook,
		// call it now
		if (typeof this.hook == 'function') 
		{
			this.hook();
		}
	}
	
  }

  //--------------------------------------------------
  this.set_ignore_case = function(value) 
  {
    // This method sets the regexp flags.
    // If value is true, sets the flags to "i".
    // If value is false, sets the flags to "".

    if (value) 
    {
      this.flags = 'i';
    } 
    else 
    {
      this.flags = '';
    }
  }

  //--------------------------------------------------
  this.debug = function(msg) 
  {
    if (this.show_debug) 
    {
      alert('FilterList: ' + msg);
    }
  }

  //==================================================
  // Initialize the object
  //==================================================
  this.init();

}

// This function will be called on the page load to clear the objects if it exists
function ClearShufflerObjects()
{
	if (MainBoxFilter)
	{
		MainBoxFilter.leftOptionsCopy = null;
		MainBoxFilter.rightOptionsCopy = null;
		MainBoxFilter = null;
	}
}