﻿/*
Filename:                                                                       
    catalogRequestForm.js                                                                
                                                                                
Description:        
    
    This file contains JavaScript code that supports the catalogRequestForm.cfc which should be found at:
    centralCode\components\catalogRequestForm.cfc
    
    Together these files create a Catalog Request Form that can be used on multiple sites to collect
    Catalog Request information in a uniform way. The Catalog Request process is automated. On the
    main site the user selects from a giant list of interests and these interests are converted into
    Catalog selections which are submitted in a way that automates much of the fullfillment process.   
    
        Individual sites may like to include there own verbage with smaller lists of interest
    selections or even specific catalogs. The idea behind these files is to isolate the form where
    the customer data is collected, and make it the same across all sites.      	        
    
    A good example of how this file is used can be found at:
    webdev\starfish\catalog.cfm
                                                                                
    History:                                                                        
    Ver         Inits   Date        Comments                                        
    1.00.00     jwl     6/12/07     Created.   
    1.00.01     jwl     9/07/07     Added option to use CAPTCHA image in handleTheSubmit.

*/

var gRegionControl      = new RegionControl();          // Global object to handle the region drop-down box.
var gInterestDataIDs    = new Array();		            // This array holds the interests that are generate by the selections on the page.
var gNumberOfCheckboxes = 0;                            // The number of interest checkboxes on the page.

// myOnLoad:
//
// This function is called after the page is loaded.
//
function myOnLoad()
{
    gNumberOfCheckboxes = document.interestForm.numberOfCheckboxes.value;  // Set our global var from a hidden form field.

    handleCountryChange('catalogInterestsForm');		// Sets up the region select box based on the country box.

} // myOnLoad						


// handleCountryChange:
//
// When the country is changed in the country drop-down box we need to figure out whether or not to display the region drop-down box, and
// if we display it, we need to populate it with the proper region names for the country that's been selected.
//
function handleCountryChange(myForm) 
{						
    var countrySelected = document.forms[myForm].country.options[document.forms[myForm].country.selectedIndex].text;

    if(countrySelected == 'United States (USA)')	// There's 2 types of USA selections for some reason.
	    countrySelected = 'United States';

    if(countrySelected == 'United States' || countrySelected == 'Canada' || countrySelected == 'Australia')	// Only these 3 countries supported with regions right now.
    {
	    document.getElementById('regionControl').style.display	= 'block';	// Display the region drop-down box.
	    document.getElementById('regionLabel').style.display	= 'block';

	    // Set the regions drop-down box to "Retrieving Data..." until the AJAX call returns.				
	    document.forms[myForm].region.options.length	= 1;	
	    document.forms[myForm].region.options[0].text	= 'Retrieving Data...';				
    	
	    gRegionControl.UpdateRegionControl(myForm, countrySelected, handleUpdateRegionControlResponse);	// Requires RegionControl.js. - Does an ajax request to get the region names and update the regions drop-down list.	
               
	    if(countrySelected == 'United States')
		    document.getElementById('zipLabel').innerHTML = 'ZIP code:&nbsp;<span class="requiredField">*</span>';
	    else	
		    document.getElementById('zipLabel').innerHTML = 'Postal Code:&nbsp;<span class="requiredField">*</span>';
    }
    else
    {
        document.getElementById('zipLabel').innerHTML = 'Postal Code:&nbsp;<span class="requiredField">*</span>';
    	
        document.getElementById('region').options.length        = 0;
	    document.getElementById('regionControl').style.display	= 'none';	// Hide the region drop-down if we don't support regions for this country.
	    document.getElementById('regionLabel').style.display 	= 'none';	
    }
    
    if(countrySelected == 'United Kingdom (UK)')
        document.forms[myForm].style.cssText = 'height:700px;';            
    else
        document.forms[myForm].style.cssText = 'height:575px;';                  
    
    getOfficeForThisCountry(countrySelected);   // This will get the office that handles the selected country, and use that info to decide whether to display the infoShare selections.      

} // handleCountryChange		


// handleUpdateRegionControlResponse:
//
// This handles the response from the AJAX call made by gRegionControl on behalf of the RegionControl class.
//
function handleUpdateRegionControlResponse()
{
    if(gRegionControl.AJAXutil.request.readyState == 4)
    {
        if(gRegionControl.AJAXutil.request.status == 200)       // Complete
        {	    
            // alert(gRegionControl.AJAXutil.request.responseText);
        		
            gRegionControl.objRegionInfo = eval('(' + gRegionControl.AJAXutil.request.responseText + ')');	
    		
            if(gRegionControl.objRegionInfo && gRegionControl.objRegionInfo.success == 'true')
            {
                gRegionControl.handleUpdateRegionControl();      // We have data! Let's update the region control.
                document.getElementById("regionLabel").innerHTML += '&nbsp;<span class="requiredField">*</span>';        
            }                              
        }
        else
            alert(	"A problem occurred in communicating between the XMLHttpRequest object and the server program.");
    }	
    	
} // handleUpdateRegionControlResponse


// getOfficeForThisCountry:
//
// This function will do an AJAX call to get the office that handles the country passed in.
//
function getOfficeForThisCountry(szCountrySelected)
{
    var url = './jsLib/regionControl/ajax/getOfficeInfo.cfm?countryName=' + szCountrySelected;               
    ajax('GET',url,true,handleInfoShareSelections);			
    
    
} // getOfficeForThisCountry				


// handleInfoShareSelections:
//
// This handles the response from the AJAX call made in getOfficeForThisCountry.
// We get the office that handles the country that's been selected in the drop-down box.
// We will use this info to either display or hide the infoShare selections.
//
function handleInfoShareSelections()
{
    var gOfficeInfo = new Object();                                                // Information about an office handled by a particular country.

    if(request.readyState == 4)
    {
        if(request.status == 200)                                                  // Complete
        {	    		
            gOfficeInfo = eval('(' + request.responseText + ')');	
                 	    		
            if(gOfficeInfo && gOfficeInfo.success == 'true')                       // We have office info.
            {   
                if(gOfficeInfo.name == 'HKE')
                    showTheInfoShareSelections();
                else  
                    hideTheInfoShareSelections();  
            }
            else
                hideTheInfoShareSelections(); 
        }
        else
            alert(	"A problem occurred in communicating between the XMLHttpRequest object and the server program.");
    }	
    	
} // handleInfoShareSelections        			


// showTheInfoShareSelections:
//
// Show the radio buttons that allow a user to determine what information they'd like to share.
// Only the UK office requires this info, the other offices don't share.
//
function showTheInfoShareSelections() 
{
    document.getElementById('infoShare').style.display	= 'block';
		
} // showTheInfoShareSelections


// hideTheInfoShareSelections:
//
// Hide the radio buttons that allow a user to determine what information they'd like to share.
// Only the UK office requires this info, the other offices don't share.
//
function hideTheInfoShareSelections() 
{
    document.getElementById('radioEmail').checked	= false;
    document.getElementById('radioPostal').checked	= false;
    document.getElementById('radioBoth').checked	= false;		
    document.getElementById('radioNone').checked	= true;
    		
    document.getElementById('infoShare').style.display	= 'none';
		
} // hideTheInfoShareSelections		


// handleRadioButton:
//
// If we type something in the input box, the appropriate radio button should turn on.
// If we leave the input box empty the radio button should turn off.
//
function handleRadioButton(szInputID, szRadioID)
{      
    // Turn all the radio buttons off
    document.getElementById('searchRadio').checked  = false;		
    document.getElementById('mailingRadio').checked = false;		
    document.getElementById('siteRadio').checked    = false;		
    document.getElementById('magRadio').checked     = false;		
    document.getElementById('friendRadio').checked  = false;		
    document.getElementById('otherRadio').checked   = false;				

    // Turn on or off the appropriate radio button.
    if(document.getElementById(szInputID).value.length > 0)
        document.getElementById(szRadioID).checked = true;
    else                            
        document.getElementById(szRadioID).checked = false;
        
    // Remove text from input boxes without checked radio boxes.
    var szTemp = document.getElementById(szInputID).value;        // Hang onto this.
    blankRadioInputFields();
    document.getElementById(szInputID).value        = szTemp;     // Restore this one.
         
} // handleRadioButton		
	
	
// blankRadioInputFields:
//
// Blank out the input fields that are associated with the radio buttons.
//
function blankRadioInputFields()
{         
    document.getElementById('mailingInput').value   = "";       
    document.getElementById('siteInput').value      = "";       
    document.getElementById('howFoundInput').value  = ""; 
            
} // blankRadioInputFields					
				
		
// selectAll:
//
// Checks all the checkboxes.
//
function selectAll() 
{	
	for(var i=0; i<gNumberOfCheckboxes; i++)						// The last checkbox selects them all.
	{
		var checkbox = document.getElementById('interest_'+i);
	
		if(document.getElementById('interest_all').checked)
			checkbox.checked = true;
		else	
			checkbox.checked = false;
	}	
	generateInterests();
	
} // selectAll		


// setSelectAll:
//
// Unchecks the select all interests checkbox.
//
function setSelectAll() 
{
    var allBoxesChecked = true;
	
    for(var i=0; i<gNumberOfCheckboxes; i++)							// The last checkbox selects them all.
    {
        if(!document.getElementById('interest_'+i).checked)
            allBoxesChecked = false;
    }					
    if(allBoxesChecked)
        document.getElementById('interest_all').checked = true;
    else                
        document.getElementById('interest_all').checked = false;
	
    generateInterests();
	
} // setSelectAll


// generateInterests:
//
// Toggle the selection icon beside the item selected.
// dataID - This is the ID of the data record in the ReqInterests table of the SQL DB for this interest.
//
function generateInterests() 
{
	gInterestDataIDs.length = 0;									// Empty the global interest array.

	for(var i=0; i<gNumberOfCheckboxes; i++)						// The last checkbox selects them all.
	{
		var checkbox = document.getElementById('interest_'+i);
					
		if(checkbox.checked)										// The dataID of the record in the ReqInterests table in the WebSiteOrders 
			manageInterestFormField(checkbox.value, 'add');			// SQL database is containted in 'checkbox.value'.
	}
	// for(var i=0; i<gInterestDataIDs.length; i++)
	//	alert(gInterestDataIDs[i]);

} // generateInterests		    


// manageInterestFormField:
//
// Add or remove the interestID passed in to/from the hidden form field.
//	interestID:		- The ID of the interest we would like to add.	
//	operation:		- Either 'add' or 'remove'.
//
function manageInterestFormField(interestID, operation) 
{
	if(operation == 'remove')							// Remove this interest.
	{
		for(i=0; i<gInterestDataIDs.length; i++)
		{
			if(gInterestDataIDs[i] == interestID)		// If we find this interestID in the array, remove it.
				gInterestDataIDs.splice(i, 1);					
		}
	}
	else												// Add this interest.
	{
		if(!thisInterestAlreadyAdded(interestID))
			gInterestDataIDs.push(interestID);
	}
		
	document.catalogInterestsForm.interests.value = "";	// Clear out whatever's in the form field.
	for(i=0; i<gInterestDataIDs.length; i++)
	{
		if(i == 0)
			document.catalogInterestsForm.interests.value += gInterestDataIDs[i];
		else	
			document.catalogInterestsForm.interests.value += ("," + gInterestDataIDs[i]);
	}
		
} // manageInterestFormField    


// thisInterestAlreadyAdded:
//
//  Returns.
//	true:	- If an interest already exists in the global array.	
//	false:	- Returns false if it does not.
//
function thisInterestAlreadyAdded(interestID) 
{
	for(var i=0; i<gInterestDataIDs.length; i++)
	{
		if(gInterestDataIDs[i] == interestID)
			return true;				
	}
	return false;
	
} // thisInterestAlreadyAdded	    

    
// handleTheSubmit:
//
//  Validate the Catalog Request form information.
//
function handleTheSubmit(preFormName, formName) 
{		
	// Make sure at least one of the interest checkboxes is checked.
	var bAcheckBoxIsChecked = false;
	// 1.00.01 a ---
	var nNumberOfCheckBoxes = document.forms[preFormName].numberOfCheckboxes.value
	// alert('Number of checkboxes:' + nNumberOfCheckBoxes);
    for(var i=0; i<nNumberOfCheckBoxes; i++)
	// 1.00.01 e ---    
    {
        if(document.getElementById('interest_' + i).checked)
            bAcheckBoxIsChecked = true; 
    }	
	if(document.getElementById('interest_all').checked)
        bAcheckBoxIsChecked = true; 			
    if(!bAcheckBoxIsChecked)
    {
    	alert("Please select at least one interest checkbox.");
		return;	        	    							    	    // Leave before validating the rest of the form.            
    }       			

    // Make sure we've selected a region if the selected country has region info.
	if(gRegionControl.regionName != "")	                        	    // If gRegionControl.regionName is null, this form doesn't have a region/state CFSELECT to validate.								
	{
		if(document.getElementById('regionControl').style.display == 'block' && document.forms[formName].region.options[0].selected == true)
		{
			alert("Please choose a " + gRegionControl.regionName + ".");
			return;		        									    // Leave before validating the rest of the form.
		}	
	}
        
	// 1.00.01 a ---    
    if(document.forms[formName].useCAPTCHA && document.forms[formName].useCAPTCHA.value == 1)		    	
    {
        if(!checkTheCAPTCHA(formName))
            return;
    }
	// 1.00.01 e ---                        
		    		    		
	// Validate the rest of the form.
	if(_CF_checkcatalogInterestsForm(document.forms[formName]))         // This calls the CF function to validate the rest of the form.
        document.forms[formName].submit();						        // If the form validates, we submit it.				
	
} // handleTheSubmit