<!-- GLOBAL VARS -->
var toggleSwitch=1;
var specialInstructionsText;

//enable request object
function GetXmlHttpObject(handler)
{ 
var objXMLHttp=null

if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

// under construction message.
function alertToDo()
{
    alert ("Not implemented.");
}

// confirm an action, usually a delete
function confirmAction(message, url)
{
	if (confirm(message))
	{
		location.href = location.protocol + "//" + location.host + url;
	}
}

// access the login cookies.
function onloadLogin()
{
    accessLoginCookie();
    var f = document.loginForm;
    f.user_name.focus();
    extractScheme();	
}

// extract scheme from addr - http or https, and append along with 
// cluster-specific TLD to required action of form (eg /login.do
// becomes https://test1.myicc.co.uk/login.do)
function extractScheme()
{
		document.loginForm.action = location.protocol + "//" + 
			document.loginForm.domain_name_excl_address_path.value + 
			document.loginForm.submit_action.value;
}

// create scheme for user exceeded limit login page

function locationProtocol()
{
		document.manageUserSessionsForm.server_protocol.value = location.protocol + "//";
		document.manageUserSessionsForm.submit();
}


// redisplay the filing history list with or without the capital docs or retrieve all flags
function redisplayFilingHistory(checkbox, url)
{
	var loc = location.protocol + "//" + location.host + url;
	if (checkbox.checked)
		location.href = loc + "&" + checkbox.name + "=true";
	else
		location.href = loc + "&" + checkbox.name + "=false";

}


// invoke download to separate window
function onloadDownloadWindow()
{
    if (document.DownloadForm.Preference.value == "auto-download")
    {
        window.open(document.DownloadForm.Url.value, "DownloadToDesktop", "resizable,scrollbars");
    }
}

// invoke download (call back function to download the order through the browser window) 
function onloadDownloadOrder()
{
	document.DownloadForm.submit();
}


// Enforce rules for when a specific town or county is selected
function enforceTownCountyRules() {

	//for (var i=0; i<document.standardSearch.country_id.length; i++)
	//{
	//	if (document.standardSearch.country_id.options[i].value == "83")
	//	{
	//		document.standardSearch.country_id.selectedIndex = i;
	//	}
	//}
	// deal with jurisdiction checkboxes
	//checkCountryOptionCompanySearch(document.standardSearch.country_id);
}

// Enforce rules for when a jurisdiction checkbox is ticked
function enforceCheckBoxRules(checkbox) {
	// other logic means that this will only have an effect, ie reset the dropdowns,
	// if NI is being unset, or RoI is being set
	if (checkbox.name == "include_northern_ireland")
	{
		// reset the town and county fields
		if (checkbox.checked == false)
		{
			if (document.standardSearch.county != null)
			{
				document.standardSearch.county.selectedIndex = 0;
			}
			
			if (document.standardSearch.town != null)
			{
				document.standardSearch.town.selectedIndex = 0;
			}
		}
	}
	
	if (checkbox.name == "include_republic_of_ireland")
	{		
		enforceROICheckBoxRules();
	}	
}

// check the roi check box rules
function enforceROICheckBoxRules()
{
	// grey out the search fields: town, county, telephone and postcode
	// ROI companies cannot be searched on these fields
	if (document.standardSearch.include_republic_of_ireland != null)
	{
		if (document.standardSearch.town != null)
		{
			document.standardSearch.town.disabled = document.standardSearch.include_republic_of_ireland.checked;
		}
		if (document.standardSearch.county != null)
		{
			document.standardSearch.county.disabled = document.standardSearch.include_republic_of_ireland.checked;
		}
		if (document.standardSearch.legal_type != null)
		{
			document.standardSearch.legal_type.disabled = document.standardSearch.include_republic_of_ireland.checked;
            document.standardSearch.legal_type.selectedIndex = 0;
		}

		// also reset these values as they won't be included in the search params
		if (document.standardSearch.phone != null)
		{	
			document.standardSearch.phone.disabled = document.standardSearch.include_republic_of_ireland.checked;
			document.standardSearch.phone.value = "";
		}
		if (document.standardSearch.postcode != null)
		{
			document.standardSearch.postcode.disabled = document.standardSearch.include_republic_of_ireland.checked;		
			document.standardSearch.postcode.value = "";
		}		
	
		if (document.standardSearch.county != null)
		{
			document.standardSearch.county.selectedIndex = 0;
		}
		
		if (document.standardSearch.town != null)
		{
			document.standardSearch.town.selectedIndex = 0;
		}
		
		if (document.standardSearch.include_business_names != null)
		{
			if ((document.standardSearch.include_republic_of_ireland.checked == true) && 
				(document.standardSearch.include_business_names.disabled == true))
			{
				document.standardSearch.include_business_names.disabled = false;
			}
			else if (document.standardSearch.include_republic_of_ireland.checked == false)
			{
				selectOrDeselectName(document.standardSearch, false, 'include_business_names');
				document.standardSearch.include_business_names.disabled = true;
			}
		}
	}
}


// Enforce rules for when a jurisdiction checkbox is ticked
function enforceCheckitCheckBoxRules() {

	if (checkbox.name == "include_republic_of_ireland")
	{
		document.standardSearch.county.selectedIndex = 0;
		document.standardSearch.town.selectedIndex = 0;
	}		
}


// check the roi check box rules for Director Search
function enforceDirectorROICheckBoxRules()
{
	// grey out the search fields: town, county and postcode
	// ROI companies cannot be searched on these fields
	if (document.stakeholderSearchForm.include_republic_of_ireland != null)
	{
		if (document.stakeholderSearchForm.company_town != null)
		{
			document.stakeholderSearchForm.company_town.disabled = document.stakeholderSearchForm.include_republic_of_ireland.checked;
			document.stakeholderSearchForm.company_town.selectedIndex = 0;
		}
		
		if (document.stakeholderSearchForm.company_postcode != null)
		{
			document.stakeholderSearchForm.company_postcode.disabled = document.stakeholderSearchForm.include_republic_of_ireland.checked;
			if (document.stakeholderSearchForm.company_postcode.disabled) 
				document.stakeholderSearchForm.company_postcode.value = "disabled when RoI selected";
			else 
				document.stakeholderSearchForm.company_postcode.value = "";
		}

		if (document.stakeholderSearchForm.postcode != null)
		{
			document.stakeholderSearchForm.postcode.disabled = document.stakeholderSearchForm.include_republic_of_ireland.checked;
			if (document.stakeholderSearchForm.postcode.disabled) 
				document.stakeholderSearchForm.postcode.value = "disabled when RoI selected";
			else 
				document.stakeholderSearchForm.postcode.value = "";
		}
		
		if (document.stakeholderSearchForm.town != null)
		{
			document.stakeholderSearchForm.town.disabled = document.stakeholderSearchForm.include_republic_of_ireland.checked;
			document.stakeholderSearchForm.town.selectedIndex = 0;
		}
		
		if (document.stakeholderSearchForm.county != null)
		{
			document.stakeholderSearchForm.county.disabled = document.stakeholderSearchForm.include_republic_of_ireland.checked;
			document.stakeholderSearchForm.county.selectedIndex = 0;
		}
		
		if (document.stakeholderSearchForm.house_name_num != null)
		{
			document.stakeholderSearchForm.house_name_num.disabled = document.stakeholderSearchForm.include_republic_of_ireland.checked;
			document.stakeholderSearchForm.house_name_num.value = "";
		}
		
		if (document.stakeholderSearchForm.street != null)
		{
			document.stakeholderSearchForm.street.disabled = document.stakeholderSearchForm.include_republic_of_ireland.checked;
			document.stakeholderSearchForm.street.value = "";
		}
	}
}


// check jurisdiction according to country on standard company search page
// and international search page; according to which country is selected
// from the dropdown from which this function was called, the user is taken
// to either the domestic search page, the online or the offline international 
// search page for the selected country
function checkCheckitCountryOptionCompanySearch(select)
{
     // NB before any form is submitted, must reset the country 
     // dropdown so that if the user clicks the
     // browser's back button the selected item will be what it was
     // originally rather than what they changed it to - see APP-2126
     var theForm = null;
     // select element may be in internationalOnlineSearchForm (online order form)
     // or placeOrderForm (offline order form)
     if (document.internationalOnlineSearchForm != null) theForm = document.internationalOnlineSearchForm;
     else if (document.placeOrderForm != null) theForm = document.placeOrderForm;
	if (select.name == "country_id")
    {
		var selInd = select.selectedIndex;
		var selCode = select.options[selInd].value;
		var selName = select.options[selInd].text;

        if (selCode == "83") //United Kingdom
        {
			document.standardSearch.include_england_scotland_wales.checked = true;
			document.standardSearch.include_northern_ireland.checked = true;
			document.standardSearch.include_republic_of_ireland.checked = false;
			if (theForm != null) theForm.reset();
			document.standardSearch.submit();
		}
        else if(selCode == "" || selCode == "Spacer") //is dividers or space
        {
            //do nothing
            return;
        }
        else
        {
            var intOnlineIds = select.form.int_online_country_id;
            var offline = true;

            if (intOnlineIds != null)
            {
                if (intOnlineIds.length == null)
                {
                    if (intOnlineIds.value == selCode)
                    {
                        offline = false;
                    }
                }
                else
                {
                    for (var index = 0; index < intOnlineIds.length; index++)
                    {
                        if (intOnlineIds[index].value == selCode)
                        {
                            offline = false;
                        }
                    }
                }
            }

            if (offline == false)
            {
                document.internationalOnlineSearch.country_id.value = selCode;
                  if (theForm != null) theForm.reset();
                document.internationalOnlineSearch.submit();
            }
            else
            {
                document.internationalSearch.country_id.value = selCode;
                if (theForm != null) theForm.reset();
                document.internationalSearch.submit();
            }
        }
//        else if(selCode == "20" || selCode == "23" || selCode == "44" ||
//        		selCode == "61" || selCode == "71" || selCode == "77" ||
//        		selCode == "111" || selCode == "116" || selCode == "138" ||
//        		selCode == "190" || selCode == "207") //is international online search
//        {
//             document.internationalOnlineSearch.country_id.value = selCode;
//  			 if (theForm != null) theForm.reset();
//             document.internationalOnlineSearch.submit();
//        }
//		else //is international offline search
//        {
//            document.internationalSearch.country_id.value = selCode;
//			if (theForm != null) theForm.reset();
//            document.internationalSearch.submit();
//        }
        
        /* following no longer reachable
		if (selCode != "83") //Great Britain - JIRA APP-1297
        {
			document.standardSearch.county.selectedIndex = 0;
			document.standardSearch.town.selectedIndex = 0;
		}*/
	}
}

// check jurisdiction according to country on standard company search page
// and international search page; according to which country is selected
// from the dropdown from which this function was called, the user is taken
// to either the domestic search page, the online or the offline international
// search page for the selected country
function checkCheckitROICountryOptionCompanySearch(select)
{
     // NB before any form is submitted, must reset the country
     // dropdown so that if the user clicks the
     // browser's back button the selected item will be what it was
     // originally rather than what they changed it to - see APP-2126
    var theForm = null;
     // select element may be in internationalOnlineSearchForm (online order form)
     // or placeOrderForm (offline order form)
     if (document.internationalOnlineSearchForm != null) theForm = document.internationalOnlineSearchForm;
     else if (document.placeOrderForm != null) theForm = document.placeOrderForm;
	if (select.name == "country_id")       
    {
		var selInd = select.selectedIndex;
		var selCode = select.options[selInd].value;
		var selName = select.options[selInd].text;

        if (selCode == "83") //United Kingdom
        {
			document.standardSearch.include_england_scotland_wales.checked = true;
			document.standardSearch.include_northern_ireland.checked = true;
			document.standardSearch.include_republic_of_ireland.checked = false;
//            if (document.standardSearch.treat_roi_as_domestic.value == "true")
//                return;
            if (theForm != null) theForm.reset();
			document.standardSearch.submit();
		}
        else if ((document.standardSearch.treat_roi_as_domestic.value == "true") && (selCode == "111")) // ROI
        {
			document.standardSearch.include_england_scotland_wales.checked = false;
			document.standardSearch.include_northern_ireland.checked = false;
			document.standardSearch.include_republic_of_ireland.checked = true;
            if (theForm != null) theForm.reset();
			document.standardSearch.submit();
		}
        else if(selCode == "" || selCode == "Spacer") //is dividers or space
        {
            //do nothing
            return;
        }
        else
        {
            var intOnlineIds = select.form.int_online_country_id;
            var offline = true;

            if (intOnlineIds != null)
            {
                if (intOnlineIds.length == null)
                {
                    if (intOnlineIds.value == selCode)
                    {
                        offline = false;
                    }
                }
                else
                {
                    for (var index = 0; index < intOnlineIds.length; index++)
                    {
                        if (intOnlineIds[index].value == selCode)
                        {
                            offline = false;
                        }
                    }
                }
            }

            if (offline == false)
            {
                document.internationalOnlineSearch.country_id.value = selCode;
                  if (theForm != null) theForm.reset();
                document.internationalOnlineSearch.submit();
            }
            else
            {
                document.internationalSearch.country_id.value = selCode;
                if (theForm != null) theForm.reset();
                document.internationalSearch.submit();
            }
        }
//        else if(selCode == "20" || selCode == "23" || selCode == "44" ||
//        		selCode == "61" || selCode == "71" || selCode == "77" ||
//        		selCode == "111" || selCode == "116" || selCode == "138" ||
//        		selCode == "190" || selCode == "207") //is international online search
//        {
//             document.internationalOnlineSearch.country_id.value = selCode;
//  			 if (theForm != null) theForm.reset();
//             document.internationalOnlineSearch.submit();
//        }
//		else //is international offline search
//        {
//            document.internationalSearch.country_id.value = selCode;
//			if (theForm != null) theForm.reset();
//            document.internationalSearch.submit();
//        }

        /* following no longer reachable
		if (selCode != "83") //Great Britain - JIRA APP-1297
        {
			document.standardSearch.county.selectedIndex = 0;
			document.standardSearch.town.selectedIndex = 0;
		}*/
	}
}

//check jurisdiction according to country on standard company search page
function checkCountryOptionCompanySearch(select)
{
     // NB before any form is submitted, must reset the country 
     // dropdown so that if the user clicks the
     // browser's back button the selected item will be what it was
     // originally rather than what they changed it to - see APP-2126
     var theForm = null;
     // select element may be in internationalOnlineSearchForm (online order form)
     // or placeOrderForm (offline order form)
     if (document.internationalOnlineSearchForm != null) theForm = document.internationalOnlineSearchForm;
     else if (document.placeOrderForm != null) theForm = document.placeOrderForm;
	if (select.name == "country_id")
    {
		var selInd = select.selectedIndex;
		var selCode = select.options[selInd].value;
		var selName = select.options[selInd].text;
		if (selCode == "82") //Great Britain
        {
        	selectJurisdictions(true, false, false);        
		}
        else if (selCode == "83") //United Kingdom
        {
        	selectJurisdictions(true, true, false);        
		}
        else if (selCode == "188") //Northern Ireland
        {
        	selectJurisdictions(false, true, false);        
		}
        else if (selCode == "111") //Republic of Ireland
        {
        	selectJurisdictions(false, false, true);        
		}
        else if (selCode == "GBROI") //Great Britain & ROI
        {
        	selectJurisdictions(true, false, true);
        }
        else if (selCode == "NIROI") //Northern Ireland & ROI
        {
        	selectJurisdictions(false, true, true);
        }
        else if (selCode == "UKROI") //United Kingdom & ROI
        {
        	selectJurisdictions(true, true, true);        
        }
        else if(selCode == "" || selCode == "Spacer") //is dividers or space
        {
            //do nothing
            return;
        }
        else //is international search
        {
            var intOnlineIds = select.form.int_online_country_id;
            var offline = true;

            if (intOnlineIds != null)
            {
                if (intOnlineIds.length == null)
                {
                    if (intOnlineIds.value == selCode)
                    {
                        offline = false;
                    }
                }
                else
                {
                    for (var index = 0; index < intOnlineIds.length; index++)
                    {
                        if (intOnlineIds[index].value == selCode)
                        {
                            offline = false;
                        }
                    }
                }
            }

            if (offline == false)
            {
                document.internationalOnlineSearch.country_id.value = selCode;
                  if (theForm != null) theForm.reset();
                document.internationalOnlineSearch.submit();
            }
            else
            {
                document.internationalSearch.country_id.value = selCode;
                if (theForm != null) theForm.reset();
                document.internationalSearch.submit();
            }
        }
        
        // enforce the ROI and NI checkbox rules
        enforceROICheckBoxRules();       
        
        setFocusOnFirstTextField(true);
	}
}

function selectJurisdictions(include_esw, include_ni, include_roi)
{
	if(document.standardSearch.include_england_scotland_wales)
    {
		document.standardSearch.include_england_scotland_wales.checked = include_esw;
	}
	
	if(document.standardSearch.include_northern_ireland)
    {
		document.standardSearch.include_northern_ireland.checked = include_ni;
	}
	
	if(document.standardSearch.include_republic_of_ireland)
    {
		document.standardSearch.include_republic_of_ireland.checked = include_roi;
	}
}

//@todo add in the eu online countries when they become available
//check jurisdiction according to country on Standard Company Search page
function checkCountryOptionInternationalSearch(select)
{
    if (select.name == "country_id")
    {
        var selInd = select.selectedIndex;
        var selCode = select.options[selInd].value;
        var selName = select.options[selInd].text;
        if (selCode == "82") //Great Britain
        {
            document.standardSearch.include_england_scotland_wales.checked = true;
            document.standardSearch.include_northern_ireland.checked = false;
            document.standardSearch.include_republic_of_ireland.checked = false;
            document.standardSearch.populate_form_from_map.value = true;
            document.standardSearch.country_for_display.value = selCode;
            document.standardSearch.submit();
        }
        else if (selCode == "83") //United Kingdom
        {
            document.standardSearch.include_england_scotland_wales.checked = true;
            document.standardSearch.include_northern_ireland.checked = true;
            document.standardSearch.include_republic_of_ireland.checked = false;
            document.standardSearch.populate_form_from_map.value = true;
            document.standardSearch.country_for_display.value = selCode;
            document.standardSearch.submit();
        }
        else if (selCode == "188") //Northern Ireland
        {
            document.standardSearch.include_england_scotland_wales.checked = false;
            document.standardSearch.include_northern_ireland.checked = true;
            document.standardSearch.include_republic_of_ireland.checked = false;
            document.standardSearch.populate_form_from_map.value = true;
            document.standardSearch.country_for_display.value = selCode;
            document.standardSearch.submit();
        }
        else if (selCode == "111") //Republic of Ireland
        {
            document.standardSearch.include_england_scotland_wales.checked = false;
            document.standardSearch.include_northern_ireland.checked = false;
            document.standardSearch.include_republic_of_ireland.checked = true;
            document.standardSearch.populate_form_from_map.value = true;
            document.standardSearch.country_for_display.value = selCode;
            document.standardSearch.submit();
        }
        else if (selCode == "GBROI") //Great Britain & ROI
        {
            document.standardSearch.include_england_scotland_wales.checked = true;
            document.standardSearch.include_northern_ireland.checked = false;
            document.standardSearch.include_republic_of_ireland.checked = true;
            document.standardSearch.populate_form_from_map.value = true;
            document.standardSearch.country_for_display.value = selCode;
            document.standardSearch.submit();
        }
        else if (selCode == "NIROI") //Northern Ireland & ROI
        {
            document.standardSearch.include_england_scotland_wales.checked = false;
            document.standardSearch.include_northern_ireland.checked = true;
            document.standardSearch.include_republic_of_ireland.checked = true;
            document.standardSearch.populate_form_from_map.value = true;
            document.standardSearch.country_for_display.value = selCode;
            document.standardSearch.submit();
        }
        else if (selCode == "UKROI") //United Kingdom & ROI
        {
            document.standardSearch.include_england_scotland_wales.checked = true;
            document.standardSearch.include_northern_ireland.checked = true;
            document.standardSearch.include_republic_of_ireland.checked = true;
            document.standardSearch.populate_form_from_map.value = true;
            document.standardSearch.country_for_display.value = selCode;
            document.standardSearch.submit();
        }
        else if(selCode == "" || selCode == "Spacer") //is dividers or space
        {
            //do nothing
            return;
        }
        else //is international search
        {
            //do nothing
        }
    }
}

//sets the cursor focus on the first non-hidden field found, ignoring the
//simple search form if requested
function setFocusOnFirstTextField(ignoreSimpleSearch)
{
    var pageForms = document.forms;
    var focusFound = false;

    if (pageForms)
    {
        for (var k = 0; k < pageForms.length; k++)
        {
            var f = document.forms[k];
            if (f && !(ignoreSimpleSearch && (f.name=='simpleSearch' || f.name=='simpleSearchNameDefault')))
		    {
		        for (var i = 0; i < f.elements.length; i++)
		        {
		            var e = f.elements[i];
                    if (e && (e.type == 'text' || e.type == 'textarea'))
		            {                        
                        var style = getStyleObject(e.name);
                        // Make sure we're not trying to focus on a non-visible or disabled element
                        
                        if (style.display != "none" && !e.disabled)
                        {                        	
							try
							{
								e.focus();
								focusFound = true;
                            	break;
                            }
                            catch(er)
                            {
                            	// continue to next element if error trying to set focus
                            	continue;
                            }
                        }
		            }
		        }
		    }

            if (focusFound)
            {
                break;
            }
        }
    }
}

//general method to read a cookie used by all scripts.
function readCookie(name)
{
    var nameEQ = name + "=";
    //alert ("cookies = "+document.cookie);
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0)
                return c.substring(nameEQ.length,c.length);
    }
    return null;
}

//save the cookie details
function createCookie(name,value,days,domain)
{
    //alert("name=<"+ name + ">; value=<"+value+">; days=<"+days+">");
    var date = new Date();
    if (days) {
        date.setTime(date.getTime()+(days*24*60*60*1000));
    }else{
        date.setTime(date.getTime()-(7*24*60*60*1000)); // minus a week.
    }
    var expires = "; expires="+date.toGMTString();
    
    // If domain is set to 'localhost', as in the case for development, 
    // the cookie doesn't get created. The following switch doesn't set 
    // the domain for the case when domain=localhost 
    if (domain == 'localhost')
    {
    	document.cookie = name+"="+value+expires+"; path=/;";
    }
    else 
    {
    	document.cookie = name+"="+value+expires+"; path=/;domain="+domain;
    }
}

//empty the form. :)
function empty(form, element)
{
  form.reset();
  element.focus();
}

// Reset a single input element to its default
function clearElementToDefault(form, name, resetValue)
{
    var els = form.elements;
    for (var count = 0; count < els.length; count++)
    {
        var el = els[count];
        if (el.name == name)
        {
            if ((el.type == "text") || (el.type == "textarea") ||
                (el.type == "hidden") || (el.type == "password"))
            {
                el.value = resetValue;
            }
            else if (el.type == "checkbox")
            {
                if (resetValue == "checked")
                    el.checked = true;
                else
                    el.checked = false;
            }
            else if (el.type == "select-one")
            {
                var opts = el.options;
                for (var count2 = 0; count2 < opts.length; count2++)
                {
                    var opt = opts[count2];
                    if (opt.value == resetValue)
                    {
                        opt.selected = true;
                        break;
                    }
                }
            }
            else if (el.type == "radio")
            {
                if (resetValue == el.value)
                    el.checked = true;
                else
                    el.checked = false;
            }
            // @todo Handle multi-selects?
        }
    }
}

/**  
 *   Sets text fields and textareas to the empty string, 
 *   sets single and multiple selects to have the first
 *   option selected, sets checkboxes to unchecked; does
 *   nothing to hidden fields or radio buttons. Used in 
 *   preference to reset in eg orderStatusDisplayGeneric.xsl
 */
function wipeForm(form)
{
    var els = form.elements;
    for (var i = 0; i < els.length; i++)
    {
        var el = els[i];
		if (el.type == "text" || el.type == "textarea")
			el.value = "";
		else if (el.type == "checkbox")
			el.checked = false;
		else if (el.type.substring(0,6) == "select")
		{
            var opts = el.options;
            for (var j = 0; j < opts.length; j++)
                opts[j].selected = false;
			opts[0].selected = true;
		}
    }
}

// Clear the specified form back to default values
// Expects elements named 'reset__' + fieldname corresponding to each field
// which is to be reset to contain the value that the field is to be reset to.
function clearFormToDefaults(form)
{
    var els = form.elements;
    for (var count = 0; count < els.length; count++)
    {
        var el = els[count];
        if ((el.name.length > "reset__".length)
            && (el.name.substring(0,7) == "reset__"))
        {
            clearElementToDefault(form, el.name.substring(7), el.value);
        }
    }
    setFocusOnFirstTextField(true);
}

// Clear the specified form back to default values and give the focus to 
// the element with the specified ID.
// Expects elements named 'reset__' + fieldname corresponding to each field
// which is to be reset to contain the value that the field is to be reset to.
function clearFormToDefaultsAndRefocus(form, idForFocus)
{
    var els = form.elements;
    for (var count = 0; count < els.length; count++)
    {
        var el = els[count];
        if ((el.name.length > "reset__".length)
            && (el.name.substring(0,7) == "reset__"))
        {
            clearElementToDefault(form, el.name.substring(7), el.value);
        }
    }
    document.getElementById(idForFocus).focus();
}

// check the delivery choice
function checkEmailDelChoice(selectValue, form, element)
{
    if (selectValue == 'E')
    {
        eval(form + "." + element + ".visible=true");
    }
    else
    {
        eval(form + "." + element + ".visible=true");
    }
}

// will return back the correct toggle value from your control check box.
// needs to be used where there are multiple forms/checkboxes on a page.
function calculateToggle(form, name)
{
   var myEls = form.elements;
   var check;
   for (i = 0; i < myEls.length; i++)
   {
       var element = myEls[i];
       if (element.type == "checkbox" && element.name == name)
       {
           check = element.checked;
       }
   }
   return check; //the value the checkbox is being set to.
}
function toggleSelectAll() {

  {
        selectOrDeselectAll(document.form, true);
    }
}
function toggleDeselectAll() {

  {
        selectOrDeselectAll(document.form, false);
    }
}
// toggle the checkbox elements
function toggleAll(form)
{
    toggleSwitch = !toggleSwitch;
    if (toggleSwitch == 1)
    {
        selectOrDeselectAll(form, false);
    }
    else
    {
        selectOrDeselectAll(form, true);
    }
}

//allows you to toggle select deselect all by name using checkbox
function toggleAllName(form, name, master)
{
   selectOrDeselectName(form, calculateToggle(form, master), name);
}

//allows you to toggle select deselect all by id using checkbox
// @todo check if this works as expecetd all the time.
function toggleAllGroup(form, elementId)
{
    toggleSwitch = !toggleSwitch;
    if (toggleSwitch == 1)
    {
        selectOrDeselectGroup(form, false, elementId);
    }
    else
    {
        selectOrDeselectGroup(form, true, elementId);
    }
}

//allows you to toggle select deselect all by id using checkbox for checkit
function toggleAllGroupCheckit(form, elementId)
{
    toggleSwitch = !toggleSwitch;
    if (toggleSwitch == 0)
    {
        selectOrDeselectGroup(form, false, elementId);
    }
    else
    {
        selectOrDeselectGroup(form, true, elementId);
    }
}

// select or deselect the checkbox elements, depending on the
// value of the parameter 'check' (true or false)
function selectOrDeselectAll(form, check)
{
    var myEls = form.elements;
    for (i = 0; i < myEls.length; i++)
    {
        if (myEls[i].type == "checkbox")
        {
            myEls[i].checked = check;
        }
    }
}

// select or deselect the checkbox elements with the given name,
// depending on the value of the parameter 'check' (true or false)
function selectOrDeselectName(form, check, name)
{
   var myEls = form.elements;
   for (i = 0; i < myEls.length; i++)
   {
       var element = myEls[i];
       if (element.type == "checkbox" && element.name == name && element.disabled == false)
       {
           element.checked = check;
       }
   }
}

// select or deselect the checkbox elements with the given id, depending on the
// value of the parameter 'check' (true or false)
function selectOrDeselectGroup(form, check, elementId)
{
    var myEls = form.elements;
    for (i = 0; i < myEls.length; i++)
    {
        var element = myEls[i];
        if (element.type == "checkbox" && element.getAttribute("id") == elementId && element.disabled == false)
        {
            element.checked = check;
        }
    }
}

function groupSelectedOrDeselected(form, check, elementId)
{
    var myEls = form.elements;
    for (i = 0; i < myEls.length; i++)
    {
        var element = myEls[i];
        if (element.type == "checkbox" && element.getAttribute("id") == elementId)
        {
        	if(element.checked != check)
        	{
        		return false;
        	}
        }
    }	
    return true;
}

//select all checkboxes with link
 function selectAllCheckBoxLink() {
	var checkflag = "false";
 var e = document.getElementsByTagName("input");
 var i;
 if (checkflag == "false") {
 for ( i = 0; i<e.length; i++) {
 if (e[i].type == "checkbox"){
 e[i].checked = true;
 }
 }
 checkflag = "true";
 } else {
 for ( i = 0; i<e.length; i++) {
 if (e[i].type == "checkbox"){
 e[i].checked = false;
 }
 }
 checkflag = "false";
 }
 }
//deselect all checkboxes with link
  function deSelectAllCheckBoxLink() {
	var checkflag = "true";
 var e = document.getElementsByTagName("input");
 var i;
 if (checkflag == "false") {
 for ( i = 0; i<e.length; i++) {
 if (e[i].type == "checkbox"){
 e[i].checked = true;
 }
 }
 checkflag = "true";
 } else {
 for ( i = 0; i<e.length; i++) {
 if (e[i].type == "checkbox"){
 e[i].checked = false;
 }
 }
 checkflag = "false";
 }
 }

function addToEmailRecipients(form)
{
    var AvailEmailRecs = form.AvailEmailRecs;
    var MaxAllowedRecipients = form.max_num_of_recipients.value;

    if(AvailEmailRecs.selectedIndex > -1)
    {
        var valueItem = AvailEmailRecs.options[AvailEmailRecs.selectedIndex];
        var EmailRecipients = form.EmailRecipients;
		var duplicate = false;
		
		// Monitoring now uses this function (doesn't have the array of delivery methods
		var deliveryAllowed = true;
		if (form.deliveryMethodSelect != null)
		{
	        // Must check the recipient has the selected delivery method details setup.
	        deliveryAllowed = validateAddRecipientDeliveryDetails(form, valueItem.value);			
		}

        if (deliveryAllowed == true)
        {
        	for (index = 0; index < EmailRecipients.length; index++)
        	{
        		var lookupItem = EmailRecipients.options[index];
    
    			if (lookupItem.value == valueItem.value)
    			{
    				duplicate = true;
    				break;
    			}
        	}
    
    		if (duplicate == false)
    		{
    			var selectedLen = EmailRecipients.options.length;
    			if (selectedLen < MaxAllowedRecipients)
    			{
    	        	EmailRecipients.options[selectedLen] = new Option(valueItem.text, valueItem.value, false, false);
    	        }
    
    	        if (EmailRecipients.options.length>=MaxAllowedRecipients)
    	        {
                    var addstyle = getStyleObject("addRecipientButton");
                    addstyle.display = "none";
    	        }
    		}
        }
        else
        {
            alert("the recipient '" + valueItem.text + "' does not have the details of the delivery method you have selected.");
        }        
    }
}
function removeFromEmailRecipients(form)
{
    var EmailRecipients = form.EmailRecipients;
    var MaxAllowedRecipients = form.max_num_of_recipients.value;

    if(EmailRecipients.selectedIndex > -1)
    {
        EmailRecipients.options[EmailRecipients.selectedIndex] = null;
		if (EmailRecipients.options.length < MaxAllowedRecipients)
		{
            var addstyle = getStyleObject("addRecipientButton");
            addstyle.display = "";
	    }
    }
}

function selectEmailRecipients()
{
    var EmailRecipients = document.getElementById("EmailRecipients");
    for(i = 0; i < EmailRecipients.options.length; i++)
    {
        EmailRecipients.options[i].selected = true;
    }
}

/**
 * Select all items in a select list so that all values are posted. 
 */
function selectAllItems(selectList)
{
    for (index = 0; index < selectList.length; index++)
    {
        var x_lookupItem = selectList.options[index];

        x_lookupItem.selected = true;
    }
}

/**
 * Select all items in a select list so that all values are posted.
 * Ensures that the list is not empty. 
 */
function selectAllItemsEmptyListDisallowed(selectList)
{
    if(selectList.length == 0)
    {
    	alert("please enter a postcode");
    	return false;
    }
    else
    {
	    for (index = 0; index < selectList.length; index++)
	    {
	        var x_lookupItem = selectList.options[index];
	        x_lookupItem.selected = true;
	    }
   	}
}

/**
 * De-select all items in a select list. 
 */
function clearAllItems(selectList)
{
    selectList.options.length = 0;
}

/**
 * Two linked fields, field_1 must have content before field_2 is enabled
 */
function enableLinkedField(field_1, field_2)
{
	if(field_1.value.length > 0)
	{
		field_2.disabled=false;
	}
	else
	{
		field_2.disabled=true;
		field_2.value="";
	}
}

function enablePositionDropdowns()
{
	// Check that the positions of the package elements are valid.
	var positionElements = document.getElementsByName("position");

	var index;
	var checkBoxes = document.getElementsByName("contained_products_id");
    for (index = 0; index < checkBoxes.length; index++)
    {
        if (checkBoxes[index].checked)
        {
        	positionElements[Math.ceil(index/2)].disabled = false;
       	}
	}
}

// opens new window and gives it focus - used to open Help
function openNewWindow (URL, windowName, windowOptions)
{
    var window = getWindow (URL, windowName, windowOptions);
}

function getWindow(URL, windowName, windowOptions)
{
    var newWindow = open (URL, windowName, windowOptions)
    newWindow.focus();
    return window;
}

function setSimpleSearchRadioButton(rBtns,buttonValue)
{
    for (i = 0; i < rBtns.length; i++)
    {
        if (rBtns[i].value == buttonValue)
        {
            rBtns[i].checked = true;
        }
    }

    var searchField = document.getElementById('search_box');
    var reg_name = document.getElementById('rb_ss_reg_name');
    var reg_num = document.getElementById('rb_ss_reg_num');

    if(reg_name.checked == true)
    {
        searchField.name = 'company_name';
    } else {
        searchField.name = 'company_key';
    }
    
       if(reg_num.checked == true)
    {
        searchField.name = 'company_key';
    } else {
        searchField.name = 'company_name';
    }
}

function setSimpleIntlSearchRadioButton(rBtns,buttonValue)
{
    for (i = 0; i < rBtns.length; i++)
    {
        if (rBtns[i].value == buttonValue)
        {
            rBtns[i].checked = true;
        }
    }

    var searchField = document.getElementById('intl_search_box');
    var reg_name = document.getElementById('rb_ss_reg_name_1');
    var reg_num = document.getElementById('rb_ss_reg_num_1');
    var duns_num = document.getElementById('rb_ss_duns_num_1');
    var tel_num = document.getElementById('rb_ss_tel_num_1');
	var helper_text = document.getElementById('helper_text');
	
	if(helper_text != null)
	{
		helper_text.innerHTML = '';
	}

    if(reg_name.checked == true)
    {
        searchField.name = 'company_name';
    } 
    else if(reg_num != null && reg_num.checked == true)
    {
    	searchField.name = 'company_key';
    	if(helper_text != null && document.getElementById('reg_num_label').innerHTML == 'Hr. number')
    	{
    		helper_text.innerHTML = 'Hr. number must be prepended with registration postcode and HR must be removed';
   		}
    } 
    else if(duns_num != null && duns_num.checked == true)
    {
    	searchField.name = 'duns_number';
    }
    else if(tel_num != null && tel_num.checked == true)
    {
    	searchField.name = 'tel_number';
    }
}

//checks if a form has at least one checkbox selected - can pass in either
//an array of checkboxes if known or all the form's elements if not known
function formHasSelectedCheckBoxes(myEls)
{
    if (myEls == null || getSelectedCheckBoxCount(myEls) == 0)
    {
        alert("please select at least one item from the list");
        return false;
    }
    return true;
}

//checks if a form has at least one checkbox selected - can pass in either
//an array of checkboxes if known or all the form's elements if not known
function formHasAtLeastTwoCheckedBoxes(myEls)
{
    if (myEls == null || getSelectedCheckBoxCount(myEls) < 2)
    {
        alert("please select at least two items from the list");
        return false;
    }
    return true;
}

//get the selected checkbox count.
function getSelectedCheckBoxCount(myEls)
{
    var selectedCBCount = 0;
    for (i = 0; i < myEls.length; i++)
    {
        if (myEls[i].type == "checkbox" && myEls[i].checked == true)
        {
        	if(myEls[i].name != "selectDeselectAll")
            {
            	selectedCBCount++;
            }
        }
    }
    return selectedCBCount;
}

// checks if a field value is null and sets another element's text to a message if it is.
function checkFieldNotEmpty(value, elemName, mess)
{
    // check value
	if(value == null || value == "")
	{
	    // get element to set the text on
		var elem = document.getElementById(elemName);
		// set text on element
		// this only works on TDs that already contain text
		// example, will set a TD containing "* required" to "Error - This is field is required"
		elem.firstChild.nodeValue = mess;
		// don't allow submit
		return false;
	}

	// allow submit
	return true;
}

function toggleOrderFilterOptions(whichLayer, hideText, displayText)
{
    var style2 = getStyleObject(whichLayer);
    var link = document.getElementById('filterLink');

    if(style2.display)
    {
        style2.display = "";
        link.innerHTML = displayText;
        link.title = displayText;
    } else {
        style2.display = "block";
        link.innerHTML = hideText;
        link.title = hideText;
        setFocusOnFirstTextField(true);
    }
}

function toggleLayer(whichLayer, hide)
{
    var style2 = getStyleObject(whichLayer);
    if (hide)
    {
        style2.display = "none";
    } else {
        style2.display = "block";
    }
}

function toggleEmailRecipients()
{
    var style2 = getStyleObject('recipientsList');
    if(style2.display == "none")
    {
        toggleLayer('recipientsLabel',false);
        toggleLayer('recipientsList',false);
        toggleLayer('recipientsButtons',false);
        toggleLayer('recipientsSelectedList',false);
        toggleLayer('recipientsAdd',false);
        toggleLayer('recipientsEdit',false);
        toggleLayer('recipientsSave',false);
    }
    else
    {
        toggleLayer('recipientsLabel',true);
        toggleLayer('recipientsList',true);
        toggleLayer('recipientsButtons',true);
        toggleLayer('recipientsSelectedList',true);
        toggleLayer('recipientsAdd',true);
        toggleLayer('recipientsEdit',true);
        toggleLayer('recipientsSave',true);
    }
}

function changeDeliveryPrefByType(typeName)
{
	// if they're changing prefs for all families of a type, show
	// an alert, otherwise not
	if (typeName)
	{
		if (window.confirm('Setting a delivery method for all families of type\n' + typeName + ' will change any modification you have\nmade to an individual family of this type.\nAre you sure you want to proceed?')) 
			document.setFamilyDeliveryPref.submit();
	}
	else document.setFamilyDeliveryPref.submit();
}

function toggleRecipientsLayers(layer1, layer2, layer3, layer4, layer5, layer6, deliveryMethodSelection, deliveryTypeId)
{
    var options = deliveryMethodSelection.options;
    var index = deliveryMethodSelection.selectedIndex;
    var emailRecipients = document.getElementById('EmailRecipients');
        
    if(
       options[index].id == deliveryTypeId || 
       options[index].text.toUpperCase() == "Email".toUpperCase() || 
       options[index].text.toUpperCase() == "Post".toUpperCase() ||
       options[index].text.toUpperCase() == "Fax".toUpperCase())
    {
        // Display the layers
        if (layer1 != null)
        {
            toggleLayer(layer1, false);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, false);
        }
        if (layer3 != null)
        {
            toggleLayer(layer3, false);
        }
        if (layer4 != null)
        {
            toggleLayer(layer4, false);
        }
        if (layer5 != null)
        {
            toggleLayer(layer5, false);
        }
        if (layer6 != null)
        {
            toggleLayer(layer6, false);
        }
        // Enable so that the valuse if selected are posted.
        if (emailRecipients != null) emailRecipients.disabled = false;
    } 
    else 
    {
        // Hide the layers
        if (layer1 != null)
        {
            toggleLayer(layer1, true);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, true);
        }
        if (layer3 != null)
        {
            toggleLayer(layer3, true);
        }
        if (layer4 != null)
        {
            toggleLayer(layer4, true);
        }
        if (layer5 != null)
        {
            toggleLayer(layer5, true);
        }
        if (layer6 != null)
        {
            toggleLayer(layer6, true);
        }
        // Disable so that the values if selected are not posted.
        if (emailRecipients != null) emailRecipients.disabled = true;
    }
}

function toggleDxNumberLayers(layer1, layer2, layer3, deliveryMethodSelection, dxDeliveryMethodId)
{    
    var options = deliveryMethodSelection.options;
    var index = deliveryMethodSelection.selectedIndex;
    var dxRecipientSelect = document.getElementById('dxRecipientSelect');
    
    if((options[index].id == dxDeliveryMethodId) || (options[index].text.toUpperCase == "DX" ))
    {        
        toggleLayer(layer1, false);
        toggleLayer(layer2, false);
        toggleLayer(layer3, false);
        
        // Enable so that the value if selected is posted.
        if (dxRecipientSelect != null)
        {
            dxRecipientSelect.disabled = false;
        }
    }
    else 
    {
        toggleLayer(layer1, true);
        toggleLayer(layer2, true);
        toggleLayer(layer3, true);
        
        // Disable so that the value if selected is not posted.
        if (dxRecipientSelect != null)
        {
            dxRecipientSelect.disabled = true;
        }
    }
}

function toggleCompanyIdDivs(visibleLayer, hiddenLayers)
{
    toggleLayer(visibleLayer, false);
    setLayerBackground("tab-"+visibleLayer, "companyIDtabSelected");
    //now hide the other layers
    for (x = 0; x < hiddenLayers.length; x++)
    {
        toggleLayer(hiddenLayers[x], true);
        setLayerBackground("tab-"+hiddenLayers[x], "companyIDtabDeSelected");
    }
}

// Set the CSS style of a nominated element
function setLayerBackground(whichLayer, colour)
{
    var style2 = document.getElementById(whichLayer);
    if (style2 != null)
    {
        style2.className = colour;
    }
}

function setRecipientsAndFieldFocus(emailDeliveryMethodId, dxDeliveryMethodId)
{
    var deliveryMethodSelection = document.getElementById('deliveryMethodSelect');
    
    if (emailDeliveryMethodId != null)
    {
        toggleRecipientsLayers('recipientsLabel',
                               'recipientsList',
                               'recipientsButtons',
                               'recipientsSelectedList',
                               'recipientsAdd',
                               'recipientsEdit',
                               deliveryMethodSelection,
                               emailDeliveryMethodId);
    }
    
    if (dxDeliveryMethodId != null)
    {
        toggleDxNumberLayers('dxNumberLabel', 
                             'dxNumber', 
                             'dxRecipientsAdd',
                             deliveryMethodSelection, 
                             dxDeliveryMethodId);
    }        
       
    setFocusOnFirstTextField(true);
}


function toggleDeliveryAddressLayers(layer1, layer2, layer3, layer4, layer5, layer6, layer7, layer8, 
                                     layer9, layer10, layer11, layer12, layer13, layer14, layer15, 
                                     deliveryMethodSelection, deliveryTypeId)
{
    var options = deliveryMethodSelection.options;
    var index = deliveryMethodSelection.selectedIndex;
    var deliveryAddress1 = document.getElementById('Address1Field');
    var deliveryAddress2 = document.getElementById('Address2Field');
    var deliveryAddress3 = document.getElementById('Address3Field');
    var deliveryTown = document.getElementById('AddressTown');
    var deliveryCounty = document.getElementById('AddressCounty');
    var deliveryPostcode = document.getElementById('AddressPostcode');
    var deliveryCountry = document.getElementById('AddressCountry');
    
    if((options[index].id == deliveryTypeId) || (options[index].text.toUpperCase == "POST" ))
    {
        // Display the layers
        if (layer1 != null)
        {
            toggleLayer(layer1, false);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, false);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, false);
        }
        if (layer3 != null)
        {        
            toggleLayer(layer3, false);
        }        
        if (layer4 != null)
        {        
            toggleLayer(layer4, false);
        }
        if (layer5 != null)
        {        
            toggleLayer(layer5, false);
        }
        if (layer6 != null)
        {        
            toggleLayer(layer6, false);
        }
        if (layer7 != null)
        {        
            toggleLayer(layer7, false);
        }
        if (layer8 != null)
        {        
            toggleLayer(layer8, false);
        }
        if (layer9 != null)
        {        
            toggleLayer(layer9, false);
        }
        if (layer10 != null)
        {        
            toggleLayer(layer10, false);
        }
        if (layer11 != null)
        {        
            toggleLayer(layer11, false);
        }
        if (layer12 != null)
        {        
            toggleLayer(layer12, false);
        }
        if (layer13 != null)
        {        
            toggleLayer(layer13, false);
        }
        if (layer14 != null)
        {        
            toggleLayer(layer14, false);
        }
        if (layer15 != null)
        {        
            toggleLayer(layer15, false);
        }
        // Enable so that the valuse if selected are posted.
        deliveryAddress1.disabled = false;
        deliveryAddress2.disabled = false;
        deliveryAddress3.disabled = false;
        deliveryTown.disabled = false;
        deliveryCounty.disabled = false;
        deliveryPostcode.disabled = false;
        deliveryCountry.disabled = false;
    } 
    else 
    {
        // Hide the layers
        if (layer1 != null)
        {
            toggleLayer(layer1, true);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, true);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, true);
        }
        if (layer3 != null)
        {        
            toggleLayer(layer3, true);
        }        
        if (layer4 != null)
        {        
            toggleLayer(layer4, true);
        }
        if (layer5 != null)
        {        
            toggleLayer(layer5, true);
        }
        if (layer6 != null)
        {        
            toggleLayer(layer6, true);
        }
        if (layer7 != null)
        {        
            toggleLayer(layer7, true);
        }
        if (layer8 != null)
        {        
            toggleLayer(layer8, true);
        }
        if (layer9 != null)
        {        
            toggleLayer(layer9, true);
        }
        if (layer10 != null)
        {        
            toggleLayer(layer10, true);
        }
        if (layer11 != null)
        {        
            toggleLayer(layer11, true);
        }
        if (layer12 != null)
        {        
            toggleLayer(layer12, true);
        }
        if (layer13 != null)
        {        
            toggleLayer(layer13, true);
        }
        if (layer14 != null)
        {        
            toggleLayer(layer14, true);
        }
        if (layer15 != null)
        {        
            toggleLayer(layer15, true);
        }
        
        // Disable so that the values if selected are not posted.
        deliveryAddress1.disabled = true;
        deliveryAddress2.disabled = true;
        deliveryAddress3.disabled = true;
        deliveryTown.disabled = true;
        deliveryCounty.disabled = true;
        deliveryPostcode.disabled = true;
        deliveryCountry.disabled = true;
    }
}

function toggleDeliveryFaxLayers(layer1, layer2, layer3, layer4, layer5, layer6, layer7, deliveryMethodSelection, deliveryTypeId)
{
    var options = deliveryMethodSelection.options;
    var index = deliveryMethodSelection.selectedIndex;
    var faxCountryCode = document.getElementById('FaxCountryCode');
    var faxAreaCode = document.getElementById('FaxAreaCode');
    var faxNumber = document.getElementById('FaxNumber');
    
    if((options[index].id == deliveryTypeId) || (options[index].text.toUpperCase == "FAX" ))
    {
        // Display the layers
        if (layer1 != null)
        {
            toggleLayer(layer1, false);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, false);
        }
        if (layer3 != null)
        {        
            toggleLayer(layer3, false);
        }
        if (layer4 != null)
        {        
            toggleLayer(layer4, false);
        }
        if (layer5 != null)
        {        
            toggleLayer(layer5, false);
        }
        if (layer6 != null)
        {        
            toggleLayer(layer6, false);
        }
        if (layer7 != null)
        {        
            toggleLayer(layer7, false);
        }
        
        // Enable so that the valuse if selected are posted.
        faxCountryCode.disabled = false; 
        faxAreaCode.disabled = false; 
        faxNumber.disabled = false;
    } 
    else 
    {
        // Hide the layers
        if (layer1 != null)
        {
            toggleLayer(layer1, true);
        }
        if (layer2 != null)
        {        
            toggleLayer(layer2, true);
        }
        if (layer3 != null)
        {        
            toggleLayer(layer3, true);
        }
        if (layer4 != null)
        {        
            toggleLayer(layer4, true);
        }
        if (layer5 != null)
        {        
            toggleLayer(layer5, true);
        }
        if (layer6 != null)
        {        
            toggleLayer(layer6, true);
        }
        if (layer7 != null)
        {        
            toggleLayer(layer7, true);
        }
        
        // Disable so that the values if selected are not posted.
        faxCountryCode.disabled = true; 
        faxAreaCode.disabled = true; 
        faxNumber.disabled = true;
    }
}

function setOfflineDeliveryDetailsAndFieldFocus(emailDeliveryMethodId)
{
    var deliveryMethodSelection = document.getElementById('deliveryMethodSelect');
    
    if (emailDeliveryMethodId != null)
    {
        toggleRecipientsLayers('recipientsLabel',
                               'recipientsList',
                               'recipientsButtons',
                               'recipientsSelectedList',
                               'recipientsAdd',
                               'recipientsEdit',
                               deliveryMethodSelection,
                               emailDeliveryMethodId);
    }
         
    setFocusOnFirstTextField(true);
}


/* Trim leading a trailing spaces from the given value */
function trimString(value)
{
    if (value == null)
    {
        return value;
    }

    var temp = new String(value);

    while (temp.length > 0)
    {
        if (temp.charAt(0) != ' ')
        {
            break;
        }
        temp = temp.substring(1);
    }

    while (temp.length > 0)
    {
        if (temp.charAt(temp.length - 1) != ' ')
        {
            break;
        }
        temp = temp.substring(0, temp.length - 1);
    }
    return temp;
}

function setSelectAllLinkAndFieldFocus()
{
    var form = document.orderSearchForm;
    var myEls = form.elements;
    var setSelectVisible = false;

    //check if form has any checkbox fields
    for (i = 0; i < myEls.length; i++)
    {
        if (myEls[i].type == "checkbox")
        {
            setSelectVisible = true;
            break;
        }
    }

    //if so, make the select all links visible
    if (setSelectVisible)
    {
        toggleLayer('topSelectLinks', false);
        toggleLayer('bottomSelectLinks', false);
    }

    setFocusOnFirstTextField(false);
}

function setCompanyIdDivsAndFieldFocus()
{
    //set favourites to display by default
    toggleCompanyIdDivs('favourites',
                         new Array('images', 'filings', 'packages',
                         'custom_packages'));

    setFocusOnFirstTextField(false);
}

/*
    Validation methods.
*/
function validateIntegerValue(field)
{
   var value = field.value;
   var i;
    for (i = 0; i < value.length; i++)
    {
        var c = value.charAt(i);
        if (((c < "0") || (c > "9")))
        {
        alert("'" + value + "' is not an integer. This preference requires an integer value.");
        field.value=value.substring(0, value.length - 1);
        }
    }
}

function validateValueNotEmpty(field)
{
	var value = field.value;
	if(value == null || value == "")
	{
		alert("The value is empty. Please enter a valid value for this preference.");
		return false;
	}
	return true;
}

/* If the day is blank default it to the first of the month */
function defaultDay(form_dd, add_dd_flag)
{
    var dd;
    if (form_dd == '' && add_dd_flag)
    {
        dd = '01';
    }
    else
    {
        dd = form_dd;
    }
    return dd;
}

/* Make a date from the supplied input day, month and year */
function makeDate(form_dd, form_mm, form_yyyy, add_dd_flag)
{
    var dd = defaultDay(form_dd, add_dd_flag);
    if ((form_dd == '') && (form_mm == '') && (form_yyyy == ''))
    {
        return null;
    }
    return new Date(form_yyyy, form_mm - 1, dd);
}

/* Validate the given date and tell the user if it's no good */
/* JS Date is lenient, so 32nd of January produces a Date of 1st Feb etc. We
   use this feature by checking that what comes out is what we put in - if it
   is different then the date must be bad */
function validateDate(form_dd, form_mm, form_yyyy, description)
{
    if (!validateDateSilently(form_dd, form_mm, form_yyyy, true))
    {
        alert('The ' + description + ' is not a valid date - please re-enter');
        return false;
    }
    return true;
}

function validateDateSilently(form_dd, form_mm, form_yyyy, add_dd_flag)
{
    var theDate = makeDate(form_dd, form_mm, form_yyyy, add_dd_flag);
    if (theDate == null)
    {
        return true;
    }
    var dd = defaultDay(form_dd, add_dd_flag);
    if ((theDate.getDate() == dd)
        && (theDate.getMonth() == (form_mm - 1))
        && (theDate.getFullYear() == form_yyyy))
    {
        return true;
    }
    return false;
}

var selectedCheckboxCount = 0;
function validateImageFormatOptions(form, checkbox)
{
	if (checkbox.name == 'selectDeselectAll')
	{
		if (checkbox.checked == false)
		{
			selectedCheckboxCount = 0;
		}	
		else
		{
			var checkBoxes = document.getElementsByName("MOMENTO_KEY");
			selectedCheckboxCount = checkBoxes.length;			
		}		
	}
	else 
	{
		if (checkbox.checked==true)
		{
			selectedCheckboxCount = selectedCheckboxCount + 1;
		}
		else
		{
			selectedCheckboxCount = selectedCheckboxCount - 1;
		}
	}

	var tiff = document.getElementById("tiff");
   	var pdf = document.getElementById("pdf");
   	
   	if (tiff != null && pdf != null)
   	{
	    if (selectedCheckboxCount > 1 && document.getElementById("tiff").checked == true)
	    {	    	
	        document.getElementById("tiff").checked = false;
	        document.getElementById("tiff").disabled = true;
	        document.getElementById("pdf").checked = true;
	        document.getElementById("pdf").disabled = true;
	    }
	    else if (selectedCheckboxCount > 1 && document.getElementById("pdf").checked == true)
	    {    	
	        document.getElementById("tiff").disabled = true;
	        document.getElementById("pdf").disabled = true;
	    }
	    else
	    {
	        document.getElementById("tiff").disabled = false;
	        document.getElementById("pdf").disabled = false;
	    }
	}
}

/*
  Page validation for the multi list basket addition page.
  Basically checks all the supplementary info is supplied and accurate.
*/
function validateSupplementaryInformation(form)
{
    var x_years = form.search_year;
    var x_addresses = form.search_address;
    var x_fromDD = form.from_DD;
    var isValid = true;

    var year_rule = /^[1-2]\d{3}/; // starts as 1 or 2 and is 4 characters long.
    var address_rule = /\w{3}/; // starts as number or a chracter 4 characters long.

    //check for year
    if (x_years != null)
    {
        isValid = checkAndShowFieldValidity(x_years, year_rule, 'supplementaryEntryError');
    }
    else if (x_addresses != null)
    {
        isValid = checkAndShowFieldValidity(x_addresses, address_rule, 'supplementaryEntryError');
    }
    else if (x_fromDD != null)
    {
        isValid = validateMultiListDateRanges(form);
    }
    return isValid;
}

/*
    find the field and if it's value fails rules validation then show the error field.
*/
function checkAndShowFieldValidity(fields, rule, pre_name)
{
    var isValid = true;
    //handle the single field not an array javascript issue.
    if (fields.length == null)
    {
        isValid = doCheckAndShow(fields, rule, pre_name);
    }
    else
    {
        //handle the full array.
        for (i = 0; i < fields.length; i++)
        {
            if (!doCheckAndShow(fields[i], rule, pre_name))
            {
                isValid = false;
            }
        }
    }
    return isValid;
}

function doCheckAndShow(element, rule, pre_name)
{
    if (!rule.test(element.value))
    {
        changeObjectVisibility(pre_name + element.getAttribute("id"), 'visible');
        return false;
    }
    else
    {
        changeObjectVisibility(pre_name + element.getAttribute("id"), 'hidden');
        return true;
    }
}

/*
    From and To fields must all be filled in.
    The actual Dates must be valid.
    The From Date must be < the To Date.
*/
function validateMultiListDateRanges(form)
{
    //check for year
    var x_fromDD = form.from_DD;
    var x_fromMM = form.from_MM;
    var x_fromYYYY = form.from_YYYY;
    var x_toDD = form.to_DD;
    var x_toMM = form.to_MM;
    var x_toYYYY = form.to_YYYY;
    var isValid = true;

    var day_rule = /[1-31]/;
    var month_rule = /[1-12]/;
    var year_rule = /^[1-2]\d{3}/; // starts as 1 or 2 and is 4 characters long.

    //check all fields exist
    if (!checkAndShowFieldValidity(x_fromDD, day_rule, 'supplementaryEntryError')
        || !checkAndShowFieldValidity(x_fromMM, month_rule, 'supplementaryEntryError')
        || !checkAndShowFieldValidity(x_fromYYYY, year_rule, 'supplementaryEntryError'))
    {
        isValid = false;
    }
    if (!checkAndShowFieldValidity(x_toDD, day_rule, 'supplementaryEntryError')
        || !checkAndShowFieldValidity(x_toMM, month_rule, 'supplementaryEntryError')
        || !checkAndShowFieldValidity(x_toYYYY, year_rule, 'supplementaryEntryError'))
    {
        isValid = false;
    }

    //check all fields make up valid dates and valid ranges
    isValid = checkValidDatesAndRanges(x_fromDD, x_fromMM, x_fromYYYY, x_toDD, x_toMM, x_toYYYY, 'supplementaryDateError');
    return isValid;
}

/*
    Accepts same size arrays of fields and then combines and validates them.
    The actual Dates must be valid.
    The From Date must be < the To Date.
*/
function checkValidDatesAndRanges(from_days, from_months, from_years, to_days, to_months, to_years, pre_name)
{
    var isValid = true;

    //handle the single field not an array javascript issue.
    if (from_days.length == null)
    {
        isValid = doCheckValidDatesAndRanges(from_days, from_months, from_years, to_days, to_months, to_years, pre_name);
    }
    else
    {
        for (i = 0; i < from_days.length; i++)
        {
            from_dd = from_days[i];
            from_mm = from_months[i];
            from_yyyy = from_years[i];
            to_dd = to_days[i];
            to_mm = to_months[i];
            to_yyyy = to_years[i];
            isValid = doCheckValidDatesAndRanges(from_dd, from_mm, from_yyyy, to_dd, to_mm, to_yyyy, pre_name);
        }
    }
    return isValid;
}

/*
    Accepts same size arrays of fields and then combines and validates them.
    The actual Dates must be valid.
    The From Date must be < the To Date.
*/
function doCheckValidDatesAndRanges(from_dd, from_mm, from_yyyy, to_dd, to_mm, to_yyyy, pre_name)
{
    var isValid = true;
    var from_valid = validateDateSilently(from_dd.value, from_mm.value, from_yyyy.value, false);
    var to_valid = validateDateSilently(to_dd.value, to_mm.value, to_yyyy.value, false);

    if (!from_valid || !to_valid)
    {
        changeObjectVisibility(pre_name + from_dd.getAttribute("id"), 'visible');
        isValid = false;
    }
    else
    {
        var from_date = makeDate(from_dd.value, from_mm.value, from_yyyy.value);
        var to_date = makeDate(to_dd.value, to_mm.value, to_yyyy.value);

        if ((from_date > to_date) || from_date == null || to_date == null)
        {
            changeObjectVisibility(pre_name + from_dd.getAttribute("id"), 'visible');
            isValid = false;
        }
        else
        {
            changeObjectVisibility(pre_name + from_dd.getAttribute("id"), 'hidden');
        }
    }
    return isValid;
}

// check for all the matching checkboxes and update the related checkbox values.
// bloody javascript doesn't like all the separate calls. So doing it all in one go.
// used to actually allow a global checkbox to control access to a master check
// box and it's slaves.
function update_all_checkboxes(form, masterCheckbox, slaveArray)
{
    var myEls = form.elements;
    for (i = 0; i < myEls.length; i++)
    {
        var element = myEls[i];
        if (element.type == "checkbox" && element.name == masterCheckbox)
        {
            //alert ("new element_id" + element.getAttribute("id"));
            //update_checkboxes(form, element.getAttribute("id"), masterCheckbox, slaveArray);
            for (x = 0; x < slaveArray.length; x++)
            {
                //disableClearCheckbox(form, element.getAttribute("id"), element.checked, slaveArray[x]);
                for (z = 0; z < myEls.length; z++)
                {
                    var zelement = myEls[z];
                    if (zelement.type == "checkbox" && zelement.getAttribute("id") == element.getAttribute("id") && zelement.name == slaveArray[x])
                    {
                        zelement.disabled = !element.checked;
                        if (!element.checked)
                            zelement.checked = element.checked;
                    }
                }
            }
        }
    }
}

// for each change to this check box then modify the related checkboxes
function update_checkboxes(form, elementId, masterCheckbox, slaveArray)
{
  var myEls = form.elements;
  for (i = 0; i < myEls.length; i++)
  {
     var element = myEls[i];
     if (element.type == "checkbox" && element.getAttribute("id") == elementId
        && element.name == masterCheckbox)
     {
          for (x = 0; x < slaveArray.length; x++)
          {
              disableClearCheckbox(form, elementId, element.checked, slaveArray[x]);
          }
     }
  }
}

//Will enable or disable the checkbox. If being disabled then the check is cleared.
function disableClearCheckbox (form, elementId, check, fieldName)
{
  var myEls = form.elements;
  for (i = 0; i < myEls.length; i++)
  {
      var element = myEls[i];
      if (element.type == "checkbox" && element.getAttribute("id") == elementId
        && element.name == fieldName)
      {
          element.disabled = !check;
          if (!check)
            element.checked = check;
      }
  }
}

// ************************
// layer utility routines *
// ************************
function getStyleObject(objectId)
{
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId))
    {
        // W3C DOM
        return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
        // MSIE 4 DOM
        return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
        // NN 4 DOM.. note: this won't find nested layers
        return document.layers[objectId];
    } else {
    	return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility)
{
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject)
    {
	    styleObject.visibility = newVisibility;
	    return true;
    }
    else
    {
	    // we couldn't find the object, so we can't change its visibility
	    return false;
    }
} // changeObjectVisibility

function moveObject(objectId, newXCoordinate, newYCoordinate)
{
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	    styleObject.left = newXCoordinate;
	    styleObject.top = newYCoordinate;
	    return true;
    }
    else
    {
        // we couldn't find the object, so we can't very well move it
        return false;
    }
} // moveObject

/*
 * Set a value based on the value of a checkbox.
 */
function setCheckbox(checkbox, valueToSet)
{
    if (checkbox.checked)
    {
        valueToSet.value = 'true';
    }
    else
    {
        valueToSet.value = 'false';
    }
}

/*
 * Print the page (thanks to Charlie for this).
 */
function printpage() 
{
    window.print(); 
}

function copyOrderLineReferences(orderLineReferenceId, pageForm)
{
    var orderRefElement = document.getElementById(orderLineReferenceId);         
    if (pageForm)
    {
        for (var i = 0; i < pageForm.elements.length; i++)
        {
             var e = pageForm.elements[i];
    
             if (e && (e.type == 'text') && (e.name == 'orderline_reference_1[]') && (e.id != orderLineReferenceId))
             {                 
                 e.value = orderRefElement.value;
             }    
        }
    }
}

/*
 * PAW: friendlier way of doing textarea truncation: when limit is reached, 
 * allows cursor movement in IE and correct scrolling in Netscape
 */
function readText(textArea, maxLength)
{
	specialInstructionsText = textArea.value.slice(0, maxLength);
}

function trimText(textArea, maxLength)
{
	if (textArea.value.length > maxLength) {
		textArea.value = specialInstructionsText;
		textArea.scrollTop = textArea.scrollHeight;
	}
}

/*
 * PAW: disables the given text input control if the given dropdown
 * doesn't have the first option selected; used via preference in eg 
 * onload of orderEditDetails.xsl
 */
function disableTextInputIfFirstDropdownItemNotSelected(textInput, dropdown)
{
	if (textInput && dropdown && !dropdown.options[0].selected) textInput.disabled = true;
}

/*
 * Just wraps up the call to toggle the order filter options
 */
function displayOrderFilterOptions()
{
    toggleOrderFilterOptions('visibleInvisible', 'hide image search options', 'display image search options');
}


/*
 * Sets focus on the specified field in the specified form
 */
function setFieldFocus(formName, fieldName)
{
	// check first if the field exists
	var field = document.getElementById(fieldName);
	
	// try two different ways: IE likes the first but not the second, vice versa for Firefox
	if (document.forms[formName] != null && document.forms[formName].elements[fieldName] != null)
		document.forms[formName].elements[fieldName].focus();
	else if (field != null)
		field.focus();
}

/* Onload script for standard search page. User may have returned to the 
   standard search page via the back button, having set the country dropdown
   to a country other than the default. In this case when they come back to
   the page it will still be set to what they set it to, and if they don't 
   notice, and submit a search, they'll be doing an international search 
   from the domestic search page, which doesn't make sense. See APP-2126.
   
   This function should be called in the onload tag of the standard search page's
   body element. If the selected item in the coutry_select dropdown isn't one of the 
   domestic countries (GB, UK, RoI, England and NI etc) it's set to Great Britain.
   
   If the default selection of the country dropdown isn't Great Britain, this function
   should be replaced as the unit value of the PAGE-LOAD-SCRIPT-COMPANY-SEARCH-STANDARD
   pref by another function, eg resetCountryDropdown(), which resets to a different
   value, defined in a service-specific JS file, eg /js/framework/checkit/general.js
*/
function resetCountryDropdownDefault()
{
	var selectElement = document.getElementById("country_id_select");
	if (selectElement)
	{
		var selectedValue = selectElement.options[selectElement.selectedIndex].value;
		//alert(selectedValue);
		if (selectedValue != 82 && selectedValue != 188 && selectedValue != 111
			&& selectedValue != 83 && selectedValue != "GBROI" &&
	        selectedValue != "NIROI" && selectedValue != "UKROI")
		{
			var selectedValue = selectElement.options[selectElement.selectedIndex].value;
			//alert(selectedValue);
			if (selectedValue != 82 && selectedValue != 188 && selectedValue != 111
				&& selectedValue != 83 && selectedValue != "NIROI" && selectedValue != "UKROI")
			{
				for (var x = 0; x < selectElement.options.length; x++)
				{
					if (selectElement.options[x].text == "Great Britain")
					{
						selectElement.options[x].selected = true;
						break;
					}
				}
			}
			// deal with jurisdiction checkboxes
			checkCountryOptionCompanySearch(selectElement);
		}
	}
}

/* message for customers clicking company identification page when they don't have the required jurisdiction privilege
*/
function displayDontHaveJurisdictionPrivMessage(supportTelNum){

	var alertString = "You do not have the jurisdiction privilege to view the selected company.";
	if(supportTelNum != "")
	{
		alertString += "\nPlease telephone " + supportTelNum + " to get this privilege.";
	}	

	alert(alertString);
	return;
}

/*message for customers clicking link for Republic of Ireland companies
from directors link
*/
function postForIsInternationalCompanyMessage(){

alert("The company you are trying to view is registered in the Republic of Ireland.\n If you wish to retrieve a report on this company goto international online on company search screen \n or contact sales@checkit.co.uk");
                
return;

}


// This is a function that returns a function that is used
// in the event listener
function getOnScrollFunction(oElement) {
    return function () {
        if (oElement._scrollSyncDirection == "horizontal" || oElement._scrollSyncDirection == "both")
            oElement.scrollLeft = event.srcElement.scrollLeft;
        if (oElement._scrollSyncDirection == "vertical" || oElement._scrollSyncDirection == "both")
            oElement.scrollTop = event.srcElement.scrollTop;
    };

}
// This function adds scroll syncronization for the fromElement to the toElement
// this means that the fromElement will be updated when the toElement is scrolled
function addScrollSynchronization(fromElement, toElement, direction) {
    removeScrollSynchronization(fromElement);
    
    fromElement._syncScroll = getOnScrollFunction(fromElement);
    fromElement._scrollSyncDirection = direction;
    fromElement._syncTo = toElement;
    toElement.attachEvent("onscroll", fromElement._syncScroll);
    // the line abobve is IE specific, and a FF equivalnet is here, but requires more thought
	//toElement.addEventListener("onscroll", fromElement._syncScroll,true);
}

// removes the scroll synchronization for an element
function removeScrollSynchronization(fromElement) {
    if (fromElement._syncTo != null)
        fromElement._syncTo.detachEvent("onscroll", fromElement._syncScroll);

    fromElement._syncTo = null;;
    fromElement._syncScroll = null;
    fromElement._scrollSyncDirection = null;
}

function onloadMonitoring()
{
    if(document.getElementById("scrollheader")!=null)
    {
        addScrollSynchronization(document.getElementById("scrollheader"), document.getElementById("scrolltable"), "horizontal");
        addScrollSynchronization(document.getElementById("scrolltable"), document.getElementById("scrollheader"), "horizontal");
    }
}

// Update the delivery time based on the change to the delivery method
function onchangeDeliveryTimescale()
{
	var originalDeliveryTimescale = document.updateOrderDetailsForm.original_delivery_timescale_id.value;
	var originalDeliveryTime = document.updateOrderDetailsForm.original_update_delivery_date_time.value;
	var deliveryTimescaleId = document.updateOrderDetailsForm.update_delivery_timescale.options[document.updateOrderDetailsForm.update_delivery_timescale.selectedIndex].value;

	// the date format we are working with
	var dateFormat = 'dd/MM/yyyy HH:mm';


	// 31000 - standard delivery time
	// 31001 - express delivery time
	if (deliveryTimescaleId == originalDeliveryTimescale)

	{
		document.updateOrderDetailsForm.update_delivery_date_time.value = originalDeliveryTime;
	}
	else if (deliveryTimescaleId == '31000')
	{
		// delivery timescale has changed from express to standard, therefore add 40 minutes

		// get the delivery time in milliseconds
		var originalTimeMilliSecs = getDateFromFormat(originalDeliveryTime, dateFormat);

		// add 40 minutes to the delivery time
		var newTime = originalTimeMilliSecs + (40 * 60000);

		// create date object and format display string
		var newDate = new Date(newTime);

		var formattedDateString = formatDate(newDate, dateFormat);

		document.updateOrderDetailsForm.update_delivery_date_time.value = formattedDateString;
	}
	else if (deliveryTimescaleId== '31001')
	{
		// delivery timescale has changed from standard to express, therefore subtract 40 minutes

		// get the delivery time in milliseconds
		var originalTimeMilliSecs = getDateFromFormat(originalDeliveryTime, dateFormat);

		// add 40 minutes to the delivery time
		var newTime = originalTimeMilliSecs - (40 * 60000);

		// create date object and format display string
		var newDate = new Date(newTime);

		var formattedDateString = formatDate(newDate, dateFormat);

		document.updateOrderDetailsForm.update_delivery_date_time.value = formattedDateString;
	}
}

// Cycle through all selected recipients and check they have the corrrect details setup for the selected delivery method.
function validateRecipientDeliveryDetails(form)
{
    var selectedRecipients = form.EmailRecipients;
    var delivery = form.deliveryMethodSelect.options[form.deliveryMethodSelect.selectedIndex].text;

    var recipientsOk = new Array();
    var recipientsInvalid = new Array();

    for (idx = 0; idx < selectedRecipients.length; idx++)
    {
        var recipientItem = selectedRecipients[idx];

        var deliveryOk = hasRecipientValidDeliveryDetails(recipientItem.value, delivery);

        if (deliveryOk == true)
        {
            recipientsOk[recipientsOk.length] =
                new Option(recipientItem.text, recipientItem.value, false, false);
        }
        else
        {
            recipientsInvalid[recipientsInvalid.length] =
                new Option(recipientItem.text, recipientItem.value, false, false);
        }
    }

    // If we have invalid recipients then remove them.
    if (recipientsInvalid.length > 0)
    {
        alert('Not all selected recipients have the selected delivery method details setup.  They will be removed from the selection.');

        clearAllItems(selectedRecipients);

        for (ctr = 0; ctr < recipientsOk.length; ctr++)
        {
            var valueItem = recipientsOk[ctr];
            var selectedLen = selectedRecipients.options.length;
            selectedRecipients.options[selectedLen] = new Option(valueItem.text, valueItem.value, false, false);
        }
    }
}

// Validates a single delivery method for a specific recipient.
function hasRecipientValidDeliveryDetails(recipient_id, deliveryMethod)
{
    var deliveryAllowed = false;
    var user = 'recipient_' + recipient_id;
    var validDeliveryMethods = document.getElementsByName(user);

    for (index = 0; index < validDeliveryMethods.length; index++)
    {
        var lookupItem = validDeliveryMethods[index];

        if (lookupItem.value == deliveryMethod)
        {
            deliveryAllowed = true;
            break;
        }
    }

    return deliveryAllowed;
}

// Validates the delivery details of the selected recipient.
function validateAddRecipientDeliveryDetails(form, recipient_id)
{
    var deliveryMethod = form.deliveryMethodSelect.options[form.deliveryMethodSelect.selectedIndex].text;
    return hasRecipientValidDeliveryDetails(recipient_id, deliveryMethod);
}

function addUnitToPublishList()
{
	var availableUnits = document.publishUnitsForm.availableUnits;
	var publishUnits = document.publishUnitsForm.publishUnits;
	
	var selectedIndex = availableUnits.selectedIndex;
			
	if (selectedIndex == -1)
	{
		alert("please select a unit to add");
		return;
	}
			
	for (i=availableUnits.options.length-1; i>=0;i--)
	{ 
		if (availableUnits.options.item(i).selected)
		{							
			var selectedUnit = availableUnits.options.item(i);
			
			publishUnits.appendChild( selectedUnit );
		}
	}
}

function removeUnitFromPublishList()
{
	var availableUnits = document.publishUnitsForm.availableUnits;
	var publishUnits = document.publishUnitsForm.publishUnits;
	
	var selectedIndex = publishUnits.selectedIndex;
	
	if (selectedIndex == -1)
	{
		alert("please select a unit to remove");
		return;
	}
	
	for (i=publishUnits.options.length-1; i>=0;i--)
	{ 
		if (publishUnits.options.item(i).selected)
		{
			var selectedUnit = publishUnits.options.item(selectedIndex);
			
			availableUnits.appendChild( selectedUnit );
		}
	}
}

function postForPublishCustomReport(form)
{
	if (form.publishUnits != null)
	{
		selectAllItems(form.publishUnits);
	}
	
	form.submit();					
}

function CompareBands(form, level , ain, bin, compare) {
			var a = document.getElementById(ain); 
			var b = document.getElementById(bin); 
		if (integerCheck(a.value, form, level)){
			if (compare == 'LOWER') {
				if (parseInt(a.value) > parseInt(b.value)) 
				{
					document.getElementById(form + 'error').innerHTML = 'Please ensure that your lower band is less than your upper band (' + a.value + ' &gt; ' + b.value + ')';
					document.getElementById(form + level + 'RISK').className="error";
				}
				else {CleanBands(form, level, ain, bin, compare);}
					}
			}
			if (compare == 'UPPER') {				
				if (integerCheck(b.value, form, level)){
				if (parseInt(a.value) > parseInt(b.value)) 
				{
					document.getElementById(form + 'error').innerHTML = 'Please ensure that your upper band is greater than your lower band (' + a.value + ' &gt; ' + b.value + ')'
					document.getElementById(form + level + 'RISK').className="error";			
				}
				
				else {CleanBands(form, level, ain, bin, compare);}
				}
			}
}

function CleanBands (form, level , ain, bin, compare) {
			var a = document.getElementById(ain); 
			var b = document.getElementById(bin); 
			document.getElementById(form + 'error').innerHTML = "";
			if (parseInt(a.value) < parseInt(b.value)) {
				document.getElementById(form + level + 'RISK').className="";
				AlterBands(form, level, ain, bin, compare);
			}
}

function AlterBands(form, level , ain, bin, compare) {
	var compareOp;
	if (compare == 'UPPER') { 
	compareOp = 'LOWER';}
	else {
	compareOp = 'UPPER';
	}


	switch(level)
	{
		case 'HIGH':
			if(compare == 'UPPER') {
				if (document.getElementById(form + 'MODERATE-RISK-DEFINITION').disabled){
					if (document.getElementById(form + 'LIMITED-RISK-DEFINITION').disabled)
						{AlterBands(form, 'LOW', ain, bin, compare);}
					else {AlterBands(form, 'MODERATE', ain, bin, compare);}
					}
				else {
					document.getElementById(form + 'MODERATE' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(bin).value) + 1;
				}
			}
		else {
				document.getElementById(form + 'HIGH' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(ain).value) - 1;
			}

		break;
		
		case 'MODERATE':
		
		if(compare == 'UPPER') {
		
			if (document.getElementById(form + 'LIMITED-RISK-DEFINITION').disabled)
			
			{AlterBands(form, 'LOW', ain, bin, compare);}
			
			else {document.getElementById(form + 'LIMITED' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(bin).value) + 1;}
			
		} else {
		
				{document.getElementById(form + 'HIGH' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(ain).value) - 1;}
		
				}
				
		break;
		
		case 'LIMITED':
				
		if (compare == 'LOWER') {
		
			if (document.getElementById(form + 'MODERATE-RISK-DEFINITION').disabled)
			
			{AlterBands(form, 'HIGH', ain, bin, compare);}
			
			else {document.getElementById(form + 'MODERATE' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(ain).value) - 1;}
			
		} else {		
			
				{document.getElementById(form + 'LOW' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(bin).value) + 1;}
			
			}
			
		break;
		
		case 'LOW':
			if(compare == 'LOWER') {
				if (document.getElementById(form + 'LIMITED-RISK-DEFINITION').disabled){
					if (document.getElementById(form + 'MODERATE-RISK-DEFINITION').disabled)
						{AlterBands(form, 'HIGH', ain, bin, compare);}
					else {AlterBands(form, 'LIMITED', ain, bin, compare);}
				}
				else {
				document.getElementById(form + 'LIMITED' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(ain).value) - 1;
				}
			}
			else {
				document.getElementById(form + 'LOW' + '-RISK-' + compareOp + '-BOUND').value = parseInt(document.getElementById(bin).value) + 1;
			}
		break;		
	}
}

function integerCheck(arg, form, level) {
		if(isNaN(parseInt(arg))){					
		document.getElementById(form + 'error').innerHTML = 'Band must be a number in the range 0 - 100 (not ' + arg +')';
		document.getElementById(form + level + 'RISK').className="error";
				return false;}
		if(parseInt(arg) < 0 || parseInt(arg) > 100 ){					
		document.getElementById(form + 'error').innerHTML = 'Band must be a number in the range 0 - 100 (not ' + arg + ')';
		document.getElementById(form + level + 'RISK').className="error";
				return false;}
		return true;
	}	
function toggleRow(form, level, alternateCheck) {
	var state = true;
	if(alternateCheck == true && document.getElementById(form + level + '-RISK-DEFINITION').disabled) {state = false;}
	else {var swapValue = 0;
		if(level == 'MODERATE') {swapValue = document.getElementById(form + 'HIGH-RISK-UPPER-BOUND').value}
		if(level == 'LIMITED') {swapValue = document.getElementById(form + 'LOW-RISK-LOWER-BOUND').value}
		document.getElementById(form + level + '-RISK-LOWER-BOUND').value = swapValue;
		document.getElementById(form + level + '-RISK-UPPER-BOUND').value = swapValue;

		if(level == 'MODERATE') {
			swapValue++;
			var newSwapValue = swapValue;
			if (document.getElementById(form + 'LIMITED-RISK-DEFINITION').disabled) {
				document.getElementById(form + 'LOW-RISK-LOWER-BOUND').value = newSwapValue;
			} else {
				document.getElementById(form + 'LIMITED-RISK-LOWER-BOUND').value = newSwapValue;
			}
		}
		if(level == 'LIMITED') {
		
			var newSwapValue = swapValue - 1;
			if (document.getElementById(form + 'MODERATE-RISK-DEFINITION').disabled) {
				document.getElementById(form + 'HIGH-RISK-UPPER-BOUND').value = newSwapValue;
			} else {
				document.getElementById(form + 'MODERATE-RISK-UPPER-BOUND').value = newSwapValue;
			}
		}}
	document.getElementById(form + level + '-RISK-LOWER-BOUND').disabled = state;
	document.getElementById(form + level + '-RISK-UPPER-BOUND').disabled = state;
	document.getElementById(form + level + '-RISK-DEFINITION').disabled = state;
	document.getElementById(form + level + '-RISK-COLOUR').disabled = state;

	if (level == 'MODERATE' && alternateCheck == 'true' && !document.getElementById(form + 'LIMITEDCHK').checked) {
		document.getElementById(form + 'LIMITEDCHK').checked = true;
		toggleRow(form, 'LIMITED', 'false');
		document.getElementById(form + 'LIMITEDCHK').checked = false;
	}


	if (level == 'LIMITED' && alternateCheck == 'true' && !document.getElementById(form + 'MODERATECHK').checked) {
		document.getElementById(form + 'MODERATECHK').checked = true;
		toggleRow(form, 'MODERATE', 'false');
		document.getElementById(form + 'MODERATECHK').checked = false;
	}	
	
}

function uncheckDisabled(form) {
	
	uncheckRow(form, 'HIGH');
	uncheckRow(form, 'MODERATE');
	uncheckRow(form, 'LIMITED');
	uncheckRow(form, 'LOW');
}

function uncheckRow(form, level) {
	if(document.getElementById(form + level + '-RISK-DEFINITION').disabled){
	document.getElementById(form + level + '-RISK-LOWER-BOUND').disabled = false;
	document.getElementById(form + level + '-RISK-UPPER-BOUND').disabled = false;
	document.getElementById(form + level + '-RISK-DEFINITION').disabled = false;
	document.getElementById(form + level + '-RISK-COLOUR').disabled = false;	
	}
}	


//javascript for Monitoring Group rules page - tick on/off a notification category checkbox
function setNotCatCheckbox(notCatId, flag)
{
    var cb = document.getElementById('notCatActive' + notCatId);
    if (cb != null)
    {
	    if(flag=='Y')
	    {
	       cb.checked = 'checked';
	    }
	    else
	    {
	        cb.checked = '';
	    }
	}
}

//javascript for Monitoring Group rules page - used to re-set the form and react on 
// change of Score and Limit only dropdown according to business requirements (Story: 32940)
function setScoreAndLimitOnly(rulesForm, flag)
{
    if(flag=='Y')
    {
        setNotCatCheckbox(1, 'Y');
        setNotCatCheckbox(2, 'N');
        setNotCatCheckbox(3, 'N');
        setNotCatCheckbox(4, 'Y');
        setNotCatCheckbox(5, 'N');
        setNotCatCheckbox(6, 'N');
        setNotCatCheckbox(7, 'N');
    }
    else
    {
        setNotCatCheckbox(1, 'Y');
        setNotCatCheckbox(2, 'Y');
        setNotCatCheckbox(3, 'Y');
        setNotCatCheckbox(4, 'Y');
        setNotCatCheckbox(5, 'Y');
        setNotCatCheckbox(6, 'Y');
        setNotCatCheckbox(7, 'Y');
    }
}

//select a value for the "only score and credit" dropdown according to 
//what categories were checked.
//Keep in mind that if Score and Limit category ids change, the new ids must be 
//updated in the script below too. (currently score id = 1, limit id = 4);
function setScoreAndLimitDropdown(rulesForm)
{
  var othersChecked = false;
  var scoreChecked = false;
  var limitChecked = false;
  
  var scoreBoxId = 'notCatActive1';
  var creditLimitBoxId = 'notCatActive4';
  
  var elements = rulesForm.elements;
  for(i=0;i < elements.length;i++)
  {
      var e = elements[i];
  
      if (e && (e.type == 'checkbox'))
      {     
          if (e.name == 'notification_category_active_cb' && e.checked == true)
          {
              if(e.id == scoreBoxId)
              {
                  scoreChecked = true;
              }
              else if (e.id == creditLimitBoxId)
              {
                  limitChecked = true;
              }
              else
              {
                  othersChecked = true;
              }
          }
      }
  }
  
  var ddEventHandler = rulesForm.only_score_and_limit.onchange;
  rulesForm.only_score_and_limit.onchange = '';
  if( scoreChecked == true && limitChecked == true && othersChecked == false )
  {
      rulesForm.only_score_and_limit.value='Y';
  }
  else
  {
      rulesForm.only_score_and_limit.value='N';
  }
  rulesForm.only_score_and_limit.onchange = ddEventHandler;
}

function addData(sourceText, targetList)
{
    addTextToOptionList(document.getElementById(sourceText).value, targetList);
}

function addTextToOptionList(sourceValue, targetList)
{
    var target = document.getElementById(targetList);

    if (sourceValue != null)
    {
        var duplicate = false;

        for (index = 0; index < target.length; index++)
        {
            var lookupItem = target.options[index];

            if (lookupItem.value == sourceValue)
            {
                duplicate = true;
                break;
            }
        }

        if (!duplicate)
        {
            var selectedLen = target.options.length;
            target.options[selectedLen] = new Option(sourceValue, sourceValue, false, false);
        }
    }
}

function clearAllListItems(selectList)
{
	var source = document.getElementById(selectList);
	source.options.length = 0;
}

function removeSelectedListItems(selectList)
{
	var target = document.getElementById(selectList);

	var index = 0;
	var max = target.length;

	while (index < max)
	{
		var lookupItem = target.options[index];

		if (lookupItem.selected == true)
		{
			target.options[index] = null;
		}
		else
		{
			index++;
		}
	}
}

function removeWhiteSpace(str)
{
	return str.replace(/^\s*|\s*$/g,'')
}

function toggleDivVisibility(divName)
{
	var div = document.getElementById(divName); 
	
	if(div.style.display == "none")
	{
		div.style.display  = "block";
	}
	else if(div.style.display  == "block")
	{
		div.style.display  = "none";
	}
}

function validateMinMaxAgeRange(minAge, maxAge)
{
	// check min is not greater than max
	if(minAge != "" && maxAge != "") 
	{
		if(minAge > maxAge)
		{
			alert("max age must be greater than min age");
			return false;
		}
	}
	return true;	
}

function checkIfContainsDecimalPlace(str)
{
	for (var i=0; i < str.length; i++) 
	{
		if (str.charAt(i) == ".")
		return true;
	}
	return false;
}

function isNumber(str)
{
	if(isNaN(str))
	{
		alert("the number(s) you entered are not valid");
    	return false;
  	}
	else 
	{
		return true;
	}
}

function validateDateRange(minDateStr, maxDateStr)
{
	var minDay = minDateStr.substring(0,2);
	var minMonth = minDateStr.substring(3,5);
	var minYear = minDateStr.substring(6,10);
	
	var maxDay = maxDateStr.substring(0,2);
	var maxMonth = maxDateStr.substring(3,5);
	var maxYear = maxDateStr.substring(6,10);
	
	if(!validateDateSilently(minDay, minMonth, minYear, false)
		|| !validateDateSilently(maxDay, maxMonth, maxYear, false) )
	{
		alert("please enter valid date(s) in the format dd/mm/yyyy");
		return false;
	}
	
	var minDate = new Date(minYear, minMonth -1, minDay);
	var maxDate = new Date(maxYear, maxMonth -1, maxDay);
	var today = new Date();
	
	// check date not in future
	if(minDate > today || maxDate > today)
	{
		alert("date cannot be in the future");
		return false;
	}
	
	// check min is not greater than max
	if(minDateStr != "" && maxDateStr != "") 
	{
		if(minDate > maxDate)
		{
			alert("max date must be greater than min date");
			return false;
		}
	}
	return true;
}

// create the registration cookies.
function onloadRegisterCookies()
{
	var f = document.loginForm;
	if (f != null)
	{
		var username = f.username.value;
        var pin = null;
        if (f.pin != null)
        {
            pin = f.pin.value;
        }
        var password = f.password.value;
		var domain = f.domainName.value;
		
		createAllEnabledCookies(username, pin,  password, domain);
	}
}

function toggleConsumerAddress2(form)
{
	if(document.getElementById("address_2").style.display == "block")
	{
		document.getElementById("address_2").style.display = "none";
		document.getElementById("address_2_label").innerHTML = "add another address";
		form.address_2_enabled.value = "false";
		
		// clear field contents of disabled address
		form.house_name_2.value = "";
		form.house_num_2.value = "";
		form.building_name_2.value = "";
		form.street1_2.value = "";
		form.town_2.value = "";		
		form.county_2.value = "";				
		form.postcode_2.value = "";
		
		// make sure the link for address 3 is not displayed when address 2 is disabled
		document.getElementById("address_3_label_div").style.display = "none";
	}
	else
	{
		document.getElementById("address_2").style.display = "block";
		document.getElementById("address_2_label").innerHTML = "remove address";
		form.address_2_enabled.value = "true";

		// make sure the link for address 3 is only displayed when address 2 is enabled
		document.getElementById("address_3_label_div").style.display = "block";
	}
}

function toggleConsumerAddress3(form)
{
	if(document.getElementById("address_3").style.display == "block")
	{
		document.getElementById("address_3").style.display = "none";
		document.getElementById("address_3_label").innerHTML = "add another address";
		form.address_3_enabled.value = "false";
		
		// clear field contents of disabled address
		form.house_name_3.value = "";
		form.house_num_3.value = "";
		form.building_name_3.value = "";
		form.street1_3.value = "";
		form.town_3.value = "";		
		form.county_3.value = "";	
		form.postcode_3.value = "";
		
		// make sure the ('add another address') link for address 2 is only visible when address 3 is disabled
		document.getElementById("address_2_label").style.visibility = "visible";
	}
	else
	{
		document.getElementById("address_3").style.display = "block";
		document.getElementById("address_3_label").innerHTML = "remove address";
		form.address_3_enabled.value = "true";
		
		// make sure the ('remove') link for address 2 is hidden when address 3 is enabled
		document.getElementById("address_2_label").style.visibility = "hidden";
	}
}

function toggleConsumerName2(form)
{
	if(document.getElementById("name_2").style.display == "block")
	{
		document.getElementById("name_2").style.display = "none";
		document.getElementById("name_2_label").innerHTML = "add another name";
		form.name_2_enabled.value = "false";
		
		// clear field contents of disabled name
		form.title_2.value = "";
		form.surname_2.value = "";
		form.forename_2.value = "";
	}
	else
	{
		document.getElementById("name_2").style.display = "block";
		document.getElementById("name_2_label").innerHTML = "remove name";
		form.name_2_enabled.value = "true";
	}
}


// generic method for selecting a given item within a select list
function selectDropDownItem(selectElement, selectedItem)
{
	for(var i=0; i < selectElement.options.length; i++)
	{
		var opt = selectElement.options[i];
		if(opt.value == selectedItem)
		{
			opt.selected = true;
		}
	}	
}