//Function to set the "from" and "to" year drop down menu on the historic data form
function setYears(formid)
{
	if(document.getElementById('all_years' + formid).checked == true)
	{
		var fromYear = document.getElementById('fromYear' + formid).options.length -1;
		
		document.getElementById('toYear' + formid).selectedIndex = 0;
		document.getElementById('fromYear' + formid).selectedIndex = 0;
	}
}

//Calling function for Ajax object
function suggestOrganisation(formID, ajaxURL, enteredText, contentDivID, inputFormField)
{
	if(enteredText != "" && enteredText.length >= 2)
	{
		var ajaxString = ajaxURL + enteredText;
		document.getElementById(contentDivID).style.display = "";
		document.getElementById(inputFormField).disabled = true;
 		objAjaxHistoricData.filterHistoricDataSet(formID, ajaxString , contentDivID, inputFormField);
 	}
}

//Mouse over function
function suggestOver(div_value) 
{
	div_value.className = 'suggest_link_over';
}

//Mouse out function
function suggestOut(div_value) 
{
	div_value.className = 'suggest_link';
}

//Click function
function setSearch(value, setToFormField, contentWrapper) 
{	
	var mod_value = replace(value,'&amp;','&');
	document.getElementById(setToFormField).value = mod_value;
	document.getElementById(contentWrapper).innerHTML = '';
	document.getElementById(contentWrapper).style.display = 'none';
}

// Replaces text with by in string
function replace(string,text,by) 
{
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

/*
 * This function is used to add a selected organisation to the multiple select menu
 */
function updateOrganisations(hiddenOrganisationsField, OrganisationToAdd, multipleSelectMenu)
{
	var current_organisations = "";
	var currentOrgItem = "";
	
	//First loop round multiple select menu and retrieve list of current organisations in it
    for (var i = 0; i < document.getElementById(multipleSelectMenu).options.length; i++) 
    {   
    	currentOrgItem = document.getElementById(multipleSelectMenu).options[i].text;
		currentOrgItem = currentOrgItem.replace(/^\s+|\s+$/g, "");
		
		//alert(currentOrgItem);
		
    	if ((currentOrgItem != "")) 
    	{
			current_organisations = current_organisations + document.getElementById(multipleSelectMenu).options[i].text + ',';
    	}
	}

	//Find out how many organisations user has already selected
	var currentSelectLength = document.getElementById(multipleSelectMenu).options.length;
	
	//If they are trying to add another organisation when they ahve already selected 10
	if(currentSelectLength == 10)
	{
		alert("Sorry but you have already selected the maximum 10 allowed companies to compare. Please remove one before adding any more");
	}
	
	//If they are allowed to select another organisation
	else
	{
		var addNewOrg = OrganisationToAdd;
		addNewOrg = replace(addNewOrg,'&amp;','&');
	
		if(addNewOrg != '')
		{
			/*
			 * If the organisation name contains the markers "()" indicating it has a Country of origin, allow it to be added
			 * to selected organisations
			**/
			if(addNewOrg.indexOf("(") > -1 && addNewOrg.indexOf(")") > -1)
			{
				//Clear the hidden field first
				document.getElementById(hiddenOrganisationsField).value = "";
				
				new_selected_organisations = replace(current_organisations,'&amp;','&');
			
	    		if (new_selected_organisations.length > 1)
	    		{
	    			new_selected_organisations = new_selected_organisations + ', '
	   	 		}
	   			new_selected_organisations = new_selected_organisations + addNewOrg;	
	       		
				document.getElementById(hiddenOrganisationsField).value = new_selected_organisations;
			
				//Now add the selected organisation to multiple select menu
				var newSelectLength = document.getElementById(multipleSelectMenu).options.length;
				document.getElementById(multipleSelectMenu).options[newSelectLength] = new Option(addNewOrg, addNewOrg, false, false);
			}
			
			//Otherwise alert user that we do not recognise the organisation selected
			else
			{
				alert("Sorry but that retailer does not seem to be in our list of organisations. " +
						"Please choose one from the drop down menu that appears.");
			}
		}
	}
}


/*
	Function for removing an Organisation from the multiple SELECT menu
	displaying all organisations associated with the article
	
	PARAMETERS: Organisation = Organisation to remove
*/
function removeOrganisation(currentOrganisationsField, OrganisationToRemove, multipleSelectMenu)
{
	//alert(OrganisationToRemove);
	
	if(OrganisationToRemove != "")
	{
		// Retrieve list of currently associated organisations from hidden form field
		var current_organisations = document.getElementById(currentOrganisationsField).value;
	
		// Create an array of the current Organisations, splitting using the comma
		var currentOrgsList = current_organisations.split(",");
	
		var newOrgsList = "";
		var currentOrgItem = "";
		/*
			Loop round the list of currently associated Organisations
			and add all the ones that are NOT to be removed to new variable
		*/
		for(var i=0; i < currentOrgsList.length ; i++) 
		{
			currentOrgItem = currentOrgsList[i];
			currentOrgItem = currentOrgItem.replace(/^\s+|\s+$/g, '');
			
			if(currentOrgItem != OrganisationToRemove && currentOrgItem != "")
			{
				
				if(i != 0)
				{
					newOrgsList = newOrgsList + ",";
				}
				newOrgsList = newOrgsList + currentOrgItem;
			}
		}
		newOrgsList = (newOrgsList.replace(/^\W+/,''));
		newOrgsList = newOrgsList.replace(/^\s+|\s+$/g, '');
		
		// Update hidden form field with new list of associated organisations
		document.getElementById(currentOrganisationsField).value = newOrgsList;
	
		/*
			Now we loop round the new list of associated organisations
			and populate the multiple SELECT menu
		*/
		newOrgslistSplit = newOrgsList.split(",");
		document.getElementById(multipleSelectMenu).options.length = newOrgslistSplit.length;
		
		for (var j = 0; j < newOrgslistSplit.length; j++) 
    	{
			document.getElementById(multipleSelectMenu).options[j].value = newOrgslistSplit[j];
			document.getElementById(multipleSelectMenu).options[j].text = newOrgslistSplit[j];
			document.getElementById(multipleSelectMenu).options[j].onClick = "removeOrganisation(this.value)";
		}
	
		//Remove final option in SELECT menu as it is not needed since all the options have been shifted up one
		document.getElementById(multipleSelectMenu).options[newOrgslistSplit.length+1]=null
	
		//alert(document.getElementById('article_organisations').value);
	}
}

/*
 * Function that validates the organisation form fields for Multiple Company Comparisons
 * and Company to Sector Comparison. If the validation completes successfully, the form is 
 * submitted to the action page.
 * 
 * No validation is necessary for Sector Comparison as all 
 * the search parameters have default values
 */
function validate(formID, organisationField, flashInstalledFieldID)
{
	//Call function to determine if flsah is installed
	setFlashInstalled(flashInstalledFieldID);
	
	/*
	 * If user accidentally selects a "to date" which is before
	 * the "from date" in their research comparisons, swap the dates around
	 * and continue
	 */
	var fromYear = document.forms[formID].fromYear.value;
	var fromYear_index = document.forms[formID].fromYear.options.selectedIndex;
	var toYear	= document.forms[formID].toYear.value;
	var toYear_index = document.forms[formID].toYear.options.selectedIndex;
	
	if(fromYear > toYear)
	{
		document.forms[formID].fromYear.options.selectedIndex = toYear_index;
		document.forms[formID].toYear.options.selectedIndex = fromYear_index;
	}
	
	//Now validate organisation name entered
	if(organisationField != "" && document.getElementById(organisationField).value == "")
	{
		alert("You must select at least one company to use for comparison purposes. \nPlease type in a company name in the text box provided");
		document.getElementById(organisationField).focus();
	}
	else
	{
		//If user has typed in an organisation name that does not contain the country of origin - which is contained within ()
		//alert user to select correct version from drop down menu
		if(document.getElementById(organisationField).value.indexOf("(") == -1 || document.getElementById(organisationField).value.indexOf(")") == -1)
		{
			alert("Sorry but that retailer does not seem to be in our list of organisations. " +
						"Please choose one from the drop down menu that appears.");
		}
		
		//Otherwise submit form
		else
		{
			document.getElementById(formID).submit();
		}
		
	}
}


/* 
 * Function that determines whether user's browser has got Flash installed.
 * The result is stored in a hidden form field which is used om the action
 * page to decide what type of graph to display (i.e. Flash or PNG)
 */
function setFlashInstalled(flashInstalledFieldID)
{
	//Look for a version of Internet Explorer that supports ActiveX (i.e., one that's
	//running on a platform other than Mac or Windows 3.1) or a browser that supports
	//the plugin property of the navigator object and that has Flash Player 2.0
	//installed.

	if ((navigator.appName == "Microsoft Internet Explorer" &&
    	navigator.appVersion.indexOf("Mac") == -1 &&   navigator.appVersion.indexOf("3.1") == -1) ||

    	(navigator.plugins && navigator.plugins["Shockwave Flash"])
                       || navigator.plugins["Shockwave Flash 2.0"])
	{

   		//Update hidden form field to say that user does have flash installed.
    	//alert("flash found");
    	document.getElementById('flashInstalled' + flashInstalledFieldID).value="true";
		
	}
	else 
	{
		//Update hidden form field to say that user does NOT have flash installed.
		document.getElementById('flashInstalled' + flashInstalledFieldID).value="false";
   		//alert("No flash");
		
	}
}