//======================================================================
//
//
//  Javascripts file
//
//  Dec 1, 2009
//
//
//
//
//======================================================================


//======================================================================
//  THE FOLLOWING FOUR FUNCTIONS ARE TIGHTLY 
//  COUPLED AND SHOULD NOT BE ALTERED - EVER !!!
//======================================================================

//These four functions effectively look at the XXX element of the 
//checkbox names (cbx_XXX[ _all || _other]) and toggle their state
// when the cbx_XXX_all is checked.
//
//MIS-NAMED should be checkBoxToggle
//
//params:
//    elem   -   imput element the function is bound to
//    formID -   id of the outer form  
//
//Called in fests_search_basic.jsp
//
function checkBoxDisableToggle(elem, formID){
             
    var allCheckBoxes = document.getElementById(formID);   
          
    //get the XXX in cbx_XXX_all
    var superTypeParamSegment = getSuperTypeSegment(elem.name);

    for(var i = 0; i < allCheckBoxes.elements.length; i++ ){ 
        
        if(allCheckBoxes[i].name.substring(0, 4) == "cbx_" &&
          //get XXX in cbx_african_XXX
          getSubTypeSegment(allCheckBoxes[i].name) == superTypeParamSegment){ 
            
            allCheckBoxes[i].checked = elem.checked;
            //allCheckBoxes[i].disabled = elem.checked;
        }
        disableOtherSubType(allCheckBoxes[i], superTypeParamSegment, elem);
    }                      
}


//the two functions below, take a string arg that
//is tokenized with a '_' char.  
//The first method returns the string that lies between
//the penultimate and ultimate delimiters and prepends
//the delimiter
function getSuperTypeSegment(superTypeParamName){
                        
    var superEndIndex = (  superTypeParamName.lastIndexOf("_")  );
        
    var firstSlice = superTypeParamName.slice(0, superEndIndex);        
    var penUltimateIndex = firstSlice.lastIndexOf("_");        
    var segment = firstSlice.slice(penUltimateIndex);
     
    return segment;
        }
        

        
//This method returns the string that lies between 
//the last delimiter and the end of the string, with 
//the delimiter prepended.        
function getSubTypeSegment(subTypeParamName){
 
    var subEndIndex =  subTypeParamName.lastIndexOf("_");    
    return subTypeParamName.substring(subEndIndex);
}


//This function TOGGLES the cbx_XXX_other checkbox
//which is the sub-type of the checked superType (all). 
//The arg subTypeElem is the 'this' pointer. There is a 
//call through to this method in checkBoxDisableToggle()
//MIS-NAMED should be toggleOtherSubtype
function disableOtherSubType(currentElem, superTypeSegment, subTypeElem){
    if(currentElem.name.substring(0, 4) == "cbx_" && 
             getSubTypeSegment(currentElem.name) == "_other" && 
             getSuperTypeSegment(currentElem.name) == superTypeSegment ){        
     
     
        //currentElem.disabled = subTypeElem.checked;
        currentElem.checked = subTypeElem.checked;
        
    }    
}  
//======================================================================
//  END OF TIGHT COUPLING
//======================================================================
        

        
        
        //this function toggles the enabled state of the textbox and clears it and 
        //toggles the specific checkboxes when the non-specific checkbox is clicked
        //Called in fest_typing_data.jsp
        function toggleTypingCheckboxes(nonSpecCbx, formID){
            var allElements = document.getElementById(formID);
            for(var i = 0; i < allElements.length; i++){
                //non-spec checkbox is checked and other
                //checkboxes are disabled and unchecked
                if(allElements[i].name.substr(0, 4) == "cbx_" && allElements[i].name != nonSpecCbx.name){
                    allElements[i].checked = false;
                    allElements[i].disabled = nonSpecCbx.checked;
                }
                //toggle enabled state of textbox
                else if(allElements[i].name == 'suggestedTypeNames'){
                    allElements[i].disabled = !nonSpecCbx.checked;
                    allElements[i].value = '';
                }               
            }                        
        } 
        
        //This function sets the _all checkbox to
        //unchecked if any of its sub-types are unchecked
        function uncheckThe_AllSupertype(formId, subtypeThisPointer){
            var allElements = document.getElementById(formId);
            var postpendString = new String('_all');
            var postpendOffset = postpendString.length;

            for(var i = 0; i < allElements.length; i++){
                
                var beginSubStringIndex = allElements[i].name.length - postpendOffset;
                if( beginSubStringIndex > -1 
                    && allElements[i].name.substr(beginSubStringIndex, allElements[i].name.length - 1) == postpendString ){

                    if(allElements[i].checked == true){
                        executeUncheck(allElements[i], subtypeThisPointer)
                    }
                }
            }
        }
        
        
        //this function takes the cbx_XXX_all element name and compares it to
        //the specific checkbox name that was unchecked.  If they are of the
        //same supertype, the cbx_XXX_all is unchecked.  A helper for uncheckThe_AllSupertype
        function executeUncheck(allElement, subtypeThisPointer){
            var separatorToken = '_';
            if(subtypeThisPointer.checked == false){
               
                var superTypeSubString = allElement.name.substr(0, allElement.name.length - 4);
                var supertypeCategoryName = superTypeSubString.substring(superTypeSubString.lastIndexOf(separatorToken) + 1, superTypeSubString.length);
                var subtypeName  = subtypeThisPointer.name;
                
                var subtypeCategoryName = subtypeName.substring(subtypeName.lastIndexOf(separatorToken) + 1, subtypeName.length);

                //test for the supertype checkbox and uncheck
                if(supertypeCategoryName == subtypeCategoryName){
                    allElement.checked = false;
                }
            }            
        }
        
        
        
   //this function resets the checkboxes and text fields
   //Called in fest_typing_data.jsp
        function resetFestivalTypingForm(formID){ 
            var allElements = document.getElementById(formID);
            for(var i = 0; i < allElements.length; i++){
                //non-spec checkbox is checked and other
                //checkboxes are disabled and unchecked
                if(allElements[i].name.substr(0, 4) == "cbx_" ){
                    allElements[i].checked = false;
                    allElements[i].disabled = false;
                }
                if(allElements[i].name == 'suggestedTypeNames'){
                    allElements[i].disabled = true;
                    allElements[i].value = '';
                }                      
            }
        }

      //this function clears a text input control
      //pass "this.id" (no quotes) as the arg.
         function clearText(thisReference){

             var isKeywordsValid = document.getElementById('isKeywordsValid');
             var isKeywordSearchBeingModified = document.getElementById('isKeywordSearchBeingModified');

             if(isKeywordsValid.value == 'yes' && isKeywordSearchBeingModified.value == 'no'){
                return thisReference.value = "";
             }

             return;
         }
        
        
      //this function assigns a value to a hidden field in 
      //login.jsp for testing whether the browser is javascript enabled
      function setJavascriptInfo(){
                var hiddenElement = document.getElementById('javascriptState');
                var elementValue = hiddenElement.value;
                hiddenElement.value = 'true';
      }  
            
            
      //this function will set the end_month to the same 
      //value as the begin month in fests_search_basic.jsp.

       function synchBeginDate_EndDate(source, target){
           /*
           var begin_month = document.getElementById(source);
           var end_month   = document.getElementById(target);
           
           end_month.value = begin_month.value;
           */
       }


//==============================================================================
// Coupled methods below set a default date range for fest_basic_search.jsp
//==============================================================================

       //this is the number of named calendar months in your date range
       //e.g. 4 would cover Jan 1 to Apr 30 and Jan 31 to Apr 30
       var minNumMonthsInRange = 2;

       //method called in <body onload="...">  Sets date range
       function setDefaultSearchDateRange(){

           var begin_month        = document.getElementById('vacation_begin_month');
           var end_month          = document.getElementById('vacation_end_month');
           var vacation_end_day   = document.getElementById('vacation_end_day');
           var vacation_begin_day = document.getElementById('vacation_begin_day');
           var vacation_end_year  = document.getElementById('vacation_end_year');

           var isSearchBeingModified = document.getElementById('isSearchBeingModified');
           var isInvalidDateEnterd = document.getElementById('isInvalidDateEnterd');
           var isKeywordSearchBeingModified = document.getElementById('isKeywordSearchBeingModified');

           if((isSearchBeingModified.value == 'false' && isInvalidDateEnterd.value == 'no')){
               begin_month.value        = getBeginMonth();
               vacation_begin_day.value = getToday();
               end_month.value          = getEndMonth();
               vacation_end_day.value   = getDaysInEndMonth();
               vacation_end_year.value  = getEndYear();
           }
       }

       //get current month
       function getBeginMonth(){
           var date = new Date();
           
           return months[date.getMonth()];
       }

       //get end month - i.e. current month + 2
       function getEndMonth(){
           
           var date = new Date();
           //jan = 0
           var testMonth = date.getMonth();

           if(testMonth < 12 - minNumMonthsInRange){
               return months[testMonth + minNumMonthsInRange];
           }
           else{
            return months[testMonth - (12 -minNumMonthsInRange)];
           }
       }

       //get current day of month - if < 10 add leading '0'
       function getToday(){
           var date = new Date();
           var dayAsNum = date.getDate();

           if(dayAsNum < 10){
               return '0' + dayAsNum;
           }

           return '' + dayAsNum;
       }

       //get last day of end month - not leap year corrected
       function getDaysInEndMonth(){
           var endMonth = getEndMonth();
           
           if(endMonth == 2)
               return '28';
           if(endMonth == 4 ||endMonth == 6 ||endMonth == 9 ||endMonth == 11 )
               return '30';
           return '31';
       }

       //get year of end month
       function getEndYear(){
           var date = new Date();
           var endYear = date.getFullYear();
           var currentMonth = date.getMonth();

           if(currentMonth > 11 - minNumMonthsInRange){
               return '' + (endYear + 1);
           }
           return '' + endYear;
       }

       var months      = new Array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12' );



//==============================================================================
// End tight coupling of date range methods
//==============================================================================


        function synchQuickSearchCountryText(){
            var selectedCountry = document.getElementById('countrySelect').value;
            if(selectedCountry == 'USA'){
                selectedCountry = 'the USA';
            }
           document.getElementById('quickSearchCountry').innerHTML = selectedCountry;
        }



//============================================================================
//  THE ARRAYS AND FUNCTION TO SYNCH COUNTRY SELECTION CHANGES WITH STATES,
//  MUST MAP PERFECTLY TO DATA STRUCTURES IN States_ProvincesData.java
//
//  NOTE THE ABOVE MAINTENENCE POINTS - and reversal of argument order
//  between interior element arrays and States_ProvincesData.states_provinces.
//  First arg below is label and second is value
//
//  The order of the two dimensional arrays must map to the index order of
//  the options in the country select control in fests_search_basic.jsp
//============================================================================


//This array does not contain the
//'Array('All US States', 'All States/Provinces')' (elements index 1) because
//it is for the new festival insert options in fest_input_basic_data.jsp
var states_provinces_db_insert = new Array(

		   new Array(
                    //----USA----
                    //first element must be "Choose State",, ""
                    //first element in 3D arrays is diplay name
                    //no slashes or dashes or double spaces in second arg
                    new Array('Choose State', ''),
		    new Array('Alabama', 'AL'),
                    new Array('Alaska', 'AK'),
                    new Array('Arizona', 'AZ'),
                    new Array('Arkansas', 'AR'),
                    new Array('California', 'CA'),
                    new Array('Colorado', 'CO'),
                    new Array('Connecticut', 'CT'),
                    new Array('Delaware', 'DE'),
                    new Array('District of Columbia', 'DC'),
                    new Array('Florida', 'FL'),
                    new Array('Georgia', 'GA'),
                    new Array('Guam', 'GU'),
                    new Array('Hawaii', 'HI'),
                    new Array('Idaho', 'ID'),
                    new Array('Illinois', 'IL'),
                    new Array('Indiana', 'IN'),
                    new Array('Iowa', 'IA'),
                    new Array('Kansas', 'KS'),
                    new Array('Kentucky', 'KY'),
                    new Array('Louisiana', 'LA'),
                    new Array('Maine', 'ME'),
                    new Array('Maryland', 'MD'),
                    new Array('Massachusetts', 'MA'),
                    new Array('Michigan', 'MI'),
                    new Array('Minnesota', 'MN'),
                    new Array('Mississippi', 'MS'),
                    new Array("Missouri", 'MO'),
                    new Array('Montana', 'MT'),
                    new Array('Nebraska', 'NE'),
                    new Array('Nevada', 'NV'),
                    new Array('New Hampshire', 'NH'),
                    new Array('New Jersey', 'NJ'),
                    new Array('New Mexico', 'NM'),
                    new Array('New York', 'NY'),
                    new Array('North Carolina', 'NC'),
                    new Array('North Dakota', 'ND'),
                    new Array('Ohio', 'OH'),
                    new Array('Oklahoma', 'OK'),
                    new Array('Oregon', 'OR'),
                    new Array('Palau', 'PW'),
                    new Array('Pennsylvania', 'PA'),
                    new Array('Puerto Rico', 'PR'),
                    new Array('Rhode Island', 'RI'),
                    new Array('South Carolina', 'SC'),
                    new Array('South Dakota', 'SD'),
                    new Array('Tennessee', 'TN'),
                    new Array('Texas', 'TX'),
                    new Array('Utah', 'UT'),
                    new Array('US Virgin Islands', 'VI'),
                    new Array('Vermont', 'VT'),
                    new Array('Virginia', 'VA'),
                    new Array('Washington', 'WA'),
                    new Array('West Virginia', 'WV'),
                    new Array('Wisconsin', 'WI'),
                    new Array('Wyoming', 'WY')
                    ),

		   new Array(
                    //----Canada----
                    //first element must be "Choose State",, ""
                    //first element in 3D arrays is diplay name
                    //no slashes or dashes or double spaces in second arg
		    new Array('Choose Province', ''),
	            new Array('Alberta', 'Alberta'),
		    new Array('British Columbia', 'British Columbia'),
		    new Array('Manitoba', 'Manitoba'),
		    new Array('New Brunswick', 'New Brunswick'),
		    new Array('New Foundland', 'New Foundland'),
		    new Array('Northwest Territories', 'Northwest Territories'),
		    new Array('Nova Scotia', 'Nova Scotia'),
		    new Array('Nunavut', 'Nunavut'),
		    new Array('Ontario', 'Ontario'),
		    new Array('Prince Edward', 'Prince Edward'),
		    new Array('Quebec', 'Quebec'),
		    new Array('Saskatchewan', 'Saskatchewan'),
		    new Array('Yukon', 'Yukon')
		    ),
                        
                   new Array(
                    //----Greece----
                    //first element must be "Choose State",, ""
                    //first element in 3D arrays is diplay name
                    //no slashes or dashes or double spaces in second arg
		    new Array('Choose Province', ''),
                    new Array('Aegean Islands', 'Aegean Islands'),
		    new Array('Athens/Attika', 'Athens Attika'),
		    new Array('Central Greece', 'Central Greece'),
		    new Array('Crete', 'Crete'),
		    new Array('Ionian Islands', 'Ionian Islands'),
		    new Array('Thessaloniki/Northern Greece', 'Thessaloniki Northern Greece'),
		    new Array('The Peloponnese', 'The Peloponnese')
                    
                   
		    )
                                        
                    //new array(...);
                    //----next country----

                    );







                //This array contains the Array('All US States', 'All States/Provinces')'
                // because it is for the search options in fests_search_basic.jsp
                var states_provinces_search = new Array(

		 new Array(
                    //****USA****
                    //first arg must be "All XXX", "All States/Provinces"
                    //first element in 3D arrays is diplay name
                    //no slashes or dashes or double spaces in second arg
		    new Array('--- All US States ---', 'All States/Provinces'),
		    new Array('Alabama', 'AL'),
                    new Array('Alaska', 'AK'),
                    new Array('Arizona', 'AZ'),
                    new Array('Arkansas', 'AR'),
                    new Array('California', 'CA'),
                    new Array('Colorado', 'CO'),
                    new Array('Connecticut', 'CT'),
                    new Array('Delaware', 'DE'),
                    new Array('District of Columbia', 'DC'),
                    new Array('Florida', 'FL'),
                    new Array('Georgia', 'GA'),
                    new Array('Guam', 'GU'),
                    new Array('Hawaii', 'HI'),
                    new Array('Idaho', 'ID'),
                    new Array('Illinois', 'IL'),
                    new Array('Indiana', 'IN'),
                    new Array('Iowa', 'IA'),
                    new Array('Kansas', 'KS'),
                    new Array('Kentucky', 'KY'),
                    new Array('Louisiana', 'LA'),
                    new Array('Maine', 'ME'),
                    new Array('Maryland', 'MD'),
                    new Array('Massachusetts', 'MA'),
                    new Array('Michigan', 'MI'),
                    new Array('Minnesota', 'MN'),
                    new Array('Mississippi', 'MS'),
                    new Array("Missouri", 'MO'),
                    new Array('Montana', 'MT'),
                    new Array('Nebraska', 'NE'),
                    new Array('Nevada', 'NV'),
                    new Array('New Hampshire', 'NH'),
                    new Array('New Jersey', 'NJ'),
                    new Array('New Mexico', 'NM'),
                    new Array('New York', 'NY'),
                    new Array('North Carolina', 'NC'),
                    new Array('North Dakota', 'ND'),
                    new Array('Ohio', 'OH'),
                    new Array('Oklahoma', 'OK'),
                    new Array('Oregon', 'OR'),
                    new Array('Palau', 'PW'),
                    new Array('Pennsylvania', 'PA'),
                    new Array('Puerto Rico', 'PR'),
                    new Array('Rhode Island', 'RI'),
                    new Array('South Carolina', 'SC'),
                    new Array('South Dakota', 'SD'),
                    new Array('Tennessee', 'TN'),
                    new Array('Texas', 'TX'),
                    new Array('Utah', 'UT'),
                    new Array('US Virgin Islands', 'VI'),
                    new Array('Vermont', 'VT'),
                    new Array('Virginia', 'VA'),
                    new Array('Washington', 'WA'),
                    new Array('West Virginia', 'WV'),
                    new Array('Wisconsin', 'WI'),
                    new Array('Wyoming', 'WY')
                    ),

		   new Array(
                    //****Canada****
                    //second arg must be "All XXX", "All States/Provinces"
                    //first element in 3D arrays is diplay name
                    //no slashes or dashes or double spaces in second arg
                    new Array('--- All Canadian Provinces ---', 'All States/Provinces'),
		    new Array('Alberta', 'Alberta'),
		    new Array('British Columbia', 'British Columbia'),
		    new Array('Manitoba', 'Manitoba'),
		    new Array('New Brunswick', 'New Brunswick'),
		    new Array('New Foundland', 'New Foundland'),
		    new Array('Northwest Territories', 'Northwest Territories'),
		    new Array('Nova Scotia', 'Nova Scotia'),
		    new Array('Nunavut', 'Nunavut'),
		    new Array('Ontario', 'Ontario'),
		    new Array('Prince Edward', 'Prince Edward'),
		    new Array('Quebec', 'Quebec'),
		    new Array('Saskatchewan', 'Saskatchewan'),
		    new Array('Yukon', 'Yukon')
		    ),

                   new Array(
                    //****Greece****
                    //first arg must be "All XXX", "All States/Provinces"
                    //first element in 3D arrays is diplay name
                    //no slashes or dashes or double spaces in second arg
		    new Array('--- All Greece ---', 'All States/Provinces'),
		    new Array('Aegean Islands', 'Aegean Islands'),
		    new Array('Athens/Attika', 'Athens Attika'),
		    new Array('Central Greece', 'Central Greece'),
		    new Array('Crete', 'Crete'),
		    new Array('Ionian Islands', 'Ionian Islands'),
		    new Array('Thessaloniki/Northern Greece', 'Thessaloniki Northern Greece'),
		    new Array('The Peloponnese', 'The Peloponnese')
                    
					)

                    //new array(...);
                    //****next country****

		);


function sync_country_states(specificArray){

        //populateStateProvincesDBInsert();

		var country_selected_index = document.getElementById('country').selectedIndex;

		var chosen_array = specificArray[country_selected_index];
		var state_selectbox = document.getElementById('state_province');

		state_selectbox.options.length = 0;

		for(var i = 0; i < chosen_array.length; i++){
			state_selectbox.options[i] = new Option(chosen_array[i][0], chosen_array[i][1]);
		}
}



//======================================================================
//  END OF SYNC COUNTRY STATES
//======================================================================

/*
 *  Function disables and clears the range text boxes in email_fests_all.jsp
 *
 */
function emailFestsIDRangeClearDisable(){
    
     var allButton = document.getElementById('all_range');
     //var rangeButton = document.getElementById('limited_range');

     if(allButton.value == 'all'){
         document.getElementById('startFestID').value = '';
         //document.getElementById('endFestID').value = '';
         document.getElementById('startFestID').disabled = true;
         //document.getElementById('endFestID').disabled = true;
     }
}


/*
 *  Function enables and clears the range text boxes in email_fests_all.jsp
 */
function emailFestsIDRangeClearEnable(){

     var rangeButton = document.getElementById('limited_range');

     if(rangeButton.value == 'range'){
         document.getElementById('startFestID').disabled = false;
         //document.getElementById('endFestID').disabled = false;
         document.getElementById('startFestID').value = '';
         //document.getElementById('endFestID').value = '';
     }
}


/*
 * disables range text boxes in email_fests_all.jsp on load
 *
 */


function disableIDRange(){

    if(document.getElementById('limited_range').checked){
        document.getElementById('startFestID').disabled = false;
        //document.getElementById('endFestID').disabled = false;
    }
    if(document.getElementById('all_range').checked){
        document.getElementById('startFestID').disabled = true;
        //document.getElementById('endFestID').disabled = true;
    }

}