
// The following code is based on:
// PickList script- By Sean Geraty (http://www.freewebs.com/sean_geraty/)
// Visit JavaScript Kit (http://www.javascriptkit.com) for this JavaScript and 100s more
// Please keep this notice intact

// Control flags for list selection and sort sequence
// Sequence is on option value (first 2 chars - can be stripped off in form processing)
// It is assumed that the select list is in sort sequence initially
var singleSelect = true;  // Allows an item to be selected once only
var sortSelect = true;  // Only effective if above flag set to true
var sortPick = true;  // Will order the picklist in sort sequence

// Initialise - invoked on load
function initIt() {
  var selectList = document.getElementById("SelectList");
  var selectOptions = selectList.options;
  var selectIndex = selectList.selectedIndex;
  var pickList = document.getElementById("PickList");
  var pickOptions = pickList.options;
  pickOptions[0] = null;  // Remove initial entry from picklist (was only used to set default width)
  if (!(selectIndex > -1)) {
    selectOptions[0].selected = true;  // Set first selected on load
    selectOptions[0].defaultSelected = true;  // In case of reset/reload
  }
  selectList.focus();  // Set focus on the selectlist
}

// Adds a selected item into the picklist
function addIt() {
  var selectList = document.getElementById("SelectList");
  var selectIndex = selectList.selectedIndex;
  var selectOptions = selectList.options;
  var pickList = document.getElementById("PickList");
  var pickOptions = pickList.options;
  var pickOLength = pickOptions.length;
  
  // An item must be selected
  while (selectIndex > -1) {
    pickOptions[pickOLength] = new Option(selectList[selectIndex].text);
    pickOptions[pickOLength].value = selectList[selectIndex].value;
    // If single selection, remove the item from the select list
    if (singleSelect) {
      selectOptions[selectIndex] = null;
    }
    selectIndex = selectList.selectedIndex;
    pickOLength = pickOptions.length;
  }
  
	//If necessary, sory list
	if (sortPick) {
	    SortSelectList("PickList", sort_criterion);
	}
    
}

// Deletes an item from the picklist
function delIt() {
  var selectList = document.getElementById("SelectList");
  var selectOptions = selectList.options;
  var selectOLength = selectOptions.length;
  var pickList = document.getElementById("PickList");
  var pickIndex = pickList.selectedIndex;
  var pickOptions = pickList.options;
  while (pickIndex > -1) {
    // If single selection, replace the item in the select list
    if (singleSelect) {
      selectOptions[selectOLength] = new Option(pickList[pickIndex].text);
      selectOptions[selectOLength].value = pickList[pickIndex].value;
    }
    pickOptions[pickIndex] = null;
    
	//If necessary, sory list
    if (sortPick) {
	    SortSelectList("PickList", sort_criterion);
	    SortSelectList("SelectList", sort_criterion);
    }
    
    pickIndex = pickList.selectedIndex;
    selectOLength = selectOptions.length;
  }
}

// Selection - invoked on submit
function selIt(btn) {
  var pickList = document.getElementById("PickList");
  var pickOptions = pickList.options;
  var pickOLength = pickOptions.length;
  if (pickOLength < 1) {
    alert("No word selections have been made.\nMake a selection by highlighting words\nand then clicking the [->] button.");
    return false;
  }

    
//	  if (pickOLength > 35) {
//	  alert("You have made a very larger number of selections.  Please\nkeep your choswn word list to below 35 words.");
//	  return false;
//  }
  
  return true;
}

// Adds all items into the picklist
function addAll() {
  var selectList = document.getElementById("SelectList");
  var selectIndex = selectList.selectedIndex;
  var selectOptions = selectList.options;
  var pickList = document.getElementById("PickList");
  var pickOptions = pickList.options;
  var pickOLength = pickOptions.length;
    
	//Loop through items
	while(selectList.length>0)
	{
		//Add option to right hand side
		pickOLength = pickOptions.length;
	    pickOptions[pickOLength] = new Option(selectList[0].text);
	    pickOptions[pickOLength].value = selectList[0].value;
		//Remove it from left hand side
	    selectOptions[0] = null;
	}  
  
	//Get new length of list
	pickOLength = pickOptions.length;
	
	//If necessary, sory list
    if (sortPick) {
	    SortSelectList("PickList", sort_criterion);
    }
    
}

// Deletes all items from the picklist
function delAll() {
  var selectList = document.getElementById("SelectList");
  var selectIndex = selectList.selectedIndex;
  var selectOptions = selectList.options;
  var pickList = document.getElementById("PickList");
  var pickOptions = pickList.options;
  var pickOLength = pickOptions.length;
    
	//Loop through items
	while(pickList.length>0)
	{
		//Add option to right hand side
		selectOLength = selectOptions.length;
	    selectOptions[selectOLength] = new Option(pickList[0].text);
	    selectOptions[selectOLength].value = pickList[0].value;
		//Remove it from left hand side
	    pickOptions[0] = null;
	}  
  
	//Get new length of list
	selectOLength = selectOptions.length;
	
	//If necessary, sory list
    if (sortPick) {
	    SortSelectList("SelectList", sort_criterion);
    }
    
}

function WLSubmitData()
{
	//If selections okay, submit the form
	if (!selIt())
		return;

	//Handle the submission of the pick list - if the pick list is 35 words or less, it will be
	//sent with the GET variables.  If longer, the words will be POSTed.
	HandleSubmissionOfPickList();	
	
	//Hide the sort criterion combo box from the URL (it's in with this form for neatness, but doesn't
	//need submitting to the next page)
	document.LayoutWordlist.ComboSortCriterion.value = "";
	
	//Get the URL target (ie. is this going to end up on a wordsearch etc.)
	var urlTarget = GetURLParameter("target").toLowerCase();
	
	//Change the form action appropriately
	if ( urlTarget == "wordsearch" )
		SubmitWordsearch();

	if ( urlTarget == "acrostics" )
		SubmitAcrostics();
		
	if ( urlTarget == "flashcard" )
		SubmitFlashcard();
		
	if ( urlTarget == "anagrams" )
		SubmitAnagrams();
		
	if ( urlTarget == "hw_exp" )
		SubmitHandwritingExpress();
		
	if ( urlTarget == "hw_adv" )
		SubmitHandwritingAdvanced();
		
	if ( urlTarget == "slideshow" )
		SubmitSlideshow();
		
	if ( urlTarget == "bingo" )
		SubmitBingo();
		
	if ( urlTarget == "spelling" )
		SubmitSpelling();
		
	if ( urlTarget == "codebreaker" )
		SubmitCodeBreaker();
		
	if ( urlTarget == "spelling_practice" )
		SubmitSpellingPractice();
		
	//Actually submit form
	document.LayoutWordlist.submit();
	
}

function HandleSubmissionOfPickList()
{
	//Get the pick list
	var pickList = document.getElementById("PickList");
  			
//	if (pickList.options.length>35)
//	{
	//	document.LayoutWordlist.VarsPosted.value = "true";	
		//document.LayoutWordlist.method = "post";
	//}
//	else	
//		document.LayoutWordlist.VarsPosted.value = "";	
	
	//Build the word list (only do this if at least one item was selected)
	if (pickList.options.length>0)
	{	
		
		//Empty the initial list
		var wordList = "";
		
		//Iterate through selected values
		for (var i=0; i<pickList.options.length; i++)
		{
			//Add the word
			if (i>0) wordList+="\n";
			wordList += pickList[i].value;
		} //endfor
		
	}

	//If word list is too long...
	if (wordList.length > 200)
	{
		document.LayoutWordlist.method = "post";		
		document.LayoutWordlist.VarsPosted.value = "true";
	}	
	else	
		document.LayoutWordlist.VarsPosted.value = "";	
	
	//Copy the word list into the form variable for submission
	document.LayoutWordlist.WordList.value = wordList;
	
}

function SubmitWordsearch()
{
	//Build URL
	var url = "word_searches.php?";
	
	//Set the form target 
	document.LayoutWordlist.action = url;
	
}

function SubmitAnagrams()
{
	//Build URL
	var url = "anagrams.php?";
	
	//Set the form target 
	document.LayoutWordlist.action = url;
	
}

function SubmitCodeBreaker()
{
	//Build URL
	var url = "code_breakers.php?";
	
	//Set the form target 
	document.LayoutWordlist.action = url;
	
}


function SubmitAcrostics()
{
	//Build URL
	var url = "acrostics.php?";
	
	//Set the form target 
	document.LayoutWordlist.action = url;
	
}

function SubmitSlideshow()
{
	//Build URL
	var url = "slideshows.php?";
	
	//Set the form target 
	document.LayoutWordlist.action = url;
	
}


function SubmitFlashcard()
{
	//Build URL
	var url = "flash_cards.php?";
		
	//Set the form target 
	document.LayoutWordlist.action = url;
		
}


function SubmitBingo()
{
	//Build URL
	var url = "bingo.php?";
		
	//Set the form target 
	document.LayoutWordlist.action = url;
		
}

function SubmitSpelling()
{
	//Build URL
	var url = "spelling_tests.php?";
		
	//Set the form target 
	document.LayoutWordlist.action = url;
		
}

function SubmitSpellingPractice()
{
	//Build URL
	var url = "spelling_practice.php?";
		
	//Set the form target 
	document.LayoutWordlist.action = url;
		
}

function SubmitHandwritingExpress()
{
	//Build URL
	var url = "handwriting_practice__express_.php?";
		
	//Set the form target 
	document.LayoutWordlist.action = url;
		
}

function SubmitHandwritingAdvanced()
{
	//Build URL
	var url = "handwriting_practice__advanced.php?";
		
	//Set the form target 
	document.LayoutWordlist.action = url;
		
}

//Sort criterion
var sort_criterion = "alphabetical";

function ChangeSortCriterion()
{
	//Get the list box
	var lb = document.getElementById("ComboSortCriterion");	
	//Get the value and set the sort criterion accordingly
	if (lb.value=="alphabetically")
		sort_criterion = "alphabetically";
	if (lb.value=="difficulty")
		sort_criterion = "difficulty";
		
	//Sort
	SortSelectList("SelectList", sort_criterion);
	SortSelectList("PickList", sort_criterion);
}



//Pick number_words random words from word list
//Set command to:
//  "easiest" for the 5 easiest words
//  "easier" for 5 easier words (taken from around 33% through the list)
//  "medium" for 5 medium words (taken from around 50% through the list)
//  "harder" for 5 harder words (taken from around 75% through the list)
//  "hardest" for 5 hardest words
//number_words = number of words to pick
function PickWords(command_in, number_words)
{
	//Get a lower case version of the command
	var command = command_in.toLowerCase();
	
	//Check command
	if ( (command!="easiest") && (command!="easier") && (command!="medium") && (command!="harder") && (command!="hardest"))
	{
		alert("PickWords called with incorrect parameter: "+command);
		return;
	}
	
	//Get the select list
	var lb = document.getElementById("SelectList");
	//Get the pick list		
	var pickList = document.getElementById("PickList");
	
	//Create an array to hold copy of values in select box
	arrTexts = new Array();

	//Keep a copy of the last length copied into array
	var lastLength = 0;
	var wordsCopied = 0;
			
	//Copy across values in select list into an array
	for(i=0; i<lb.length; i++)  {
		//Only copy the word if...
		// a) less than number_words words have been copied so far
		// b) more than number_words words have been copied, but the new word coming in is the same length as the previous one
		if ( (wordsCopied<number_words) || (lb.options[i].text.length <= lastLength) ) {
			//Copy the word
			arrTexts[i] = lb.options[i].text;
			//Get a copy of this word's length
			lastLength = arrTexts[i].length;
		} //end if
	} //end for
	
	//Seed the random number generator
	Randomize();
	
	//Randomize order of array, so that words are randomized, but kept in sets of length
	//If we are being asked to find the hardest words, reverse the search
	if (command=="hardest")
		arrTexts.sort(SortReverseRandomizeByDifficulty);
	else
		arrTexts.sort(SortRandomizeByDifficulty);
		
	//Calculate the start index
	var startIndex = 0;
	
	//For easier difficulty, calculate the start position based on the index one quarter through the array
	if (command=="easier")
		startIndex = ((arrTexts.length - number_words)*0.25) | 0;	
	//For medium difficulty, calculate the start position based on the central (median) index
	if (command=="medium")
		startIndex = ((arrTexts.length - number_words)*0.5) | 0;
	//For harder difficulty, calculate the start position based on the index three quarters through the array
	if (command=="harder")
		startIndex = ((arrTexts.length - number_words)*0.75) | 0;	
	
	//Check there are five elements after the start index - if there aren't, shuffle back a bit
	if ( (startIndex+number_words) > arrTexts.length)
		startIndex = arrTexts.length-number_words;
	//Check haven't underflown beneath the zero index
	if (startIndex<0)
		startIndex=0;
		
	//Now pick the first five (if there are that many)
	var finalIndex = startIndex + number_words;	
	if (finalIndex >= arrTexts.length)
		finalIndex = arrTexts.length;

	//Get quick reference into options of pick list
	var pickOptions = pickList.options;
	//Get length of pick list
	var pickOLength = pickOptions.length;
  
	//Loop through and add one at a time to the pick list
	for (var i=startIndex; i<finalIndex; i++)
	{
		//Add option to right hand side
	    pickOptions[pickOLength] = new Option(arrTexts[i]);
	    pickOptions[pickOLength].value = arrTexts[i];
	    //Get the new length of the list
		pickOLength = pickOptions.length;
	}
	
	//Get a quick reference into the options of the select list
	var selectOptions = lb.options;
	
	//Loop through and remove items from the select list
	for (var i=0; i<selectOptions.length; i++)
	{
		//For each item in the select list, loop through the options that have been
		//copied into the pick list
		for (var j=startIndex; j<finalIndex; j++)
		{
			//If item is found, delete it
			if (selectOptions[i].value.toLowerCase() == arrTexts[j].toLowerCase())
			{
				//Delete item from array
				selectOptions[i] = null;	
				//Move "i" a step back, to account for shortened array
				i--;
				//Quit this for-j loop, we'll need to start this iteration of i again
				break;
			}
			
		} //endfor j
		
	} //endfor i
	
	//Sort
	SortSelectList("SelectList", sort_criterion);
	SortSelectList("PickList", sort_criterion);
	
}


//Change language
function ChangeLanguage()
{
	//Get the list box value
	var lb = document.getElementById("lang").value;
	
	//Reload the page with the new language 
	window.location='word_lists.php?lang='+lb;
}
