
// index.js
// handler for the index page(s)

/*
   A hidden field carries error info from the form:

inputError : error msg code to be caught by the JSP code on the error page and the corresponding
error message will  be displayed on top of the page.

The decision on which page to go is made by the function
process(formName,successPage,errorPage)
in index.jsp.

the function is called by clicking the 'Search' button. Just give it the urls of the pages.

*/
// errors . Codes are defined in page specs
// ----------------------------------------
// .20 city or state at least
// .21 search on us only
// .22 checkin after checkout
// .23 checkin = checkout
// .24 checkin before today
// .25 invalid date
// .26 stay too long
// .27 maps unavailable
// .28 too many features
// .29 too far out in the future
// ----------------------------------------



// DEBUGGGING
var DEBUG_SWITCH = 0;

function DBG(msg)
{
   if( DEBUG_SWITCH == 1 )
   		alert(msg);
}



//--------------------------------------------------------------------------------------------
				// E R R O R    H A N D L I N G
// -------------------------------------------------------------------------------------------


function setErrCode(form,code)
{
   if(form.inputError != null)
       form.inputError.value = code;

   //DBG('err code is ' + code);
}

function resetErr(form)
{
   setErrCode(form,'');
}

//----------------------------------------------------
// when some processing is required and we need to make
// some decision based on err or success, and pass the err
// to a specific page

function process(form, successPath, failurePath)
{
    // call the err hdlers (dateValidator.js)so that any err is stored in errFields
	// array (commonErr.js). Do not return false, since we have
	// to display possible errors on the failure page, not on this page.
	resetErr(form);
	if( ! okLocation(form) || ! okDates(form) )
	      ;// short-circuit and continue

	// fill-in the dates, even if error, since those need to be displayed on error page anyway..
	fillInDates(form);

	(form.inputError.value == '') ? proceed(form, successPath)
	                           : proceed(form, failurePath) ;

	return true;
}

//---------------------------------------------------
function okLocation(f)
{
     // all fields must exist, otherwise the check is not needed
   		if( f.country == null || f.city == null || f.stateProvince == null )
			return true;

   		// adapt to different USA values that might be out there...
		var cntry = '';
		if(f.country.options != null)
   			cntry = f.country.options[f.country.selectedIndex].value ;
		else
			cntry = f.country.value ;

		var usaSelected = ( cntry == "US");

        var noCity = ( f.city.value == '' || f.city.value == 'Enter city here' );
		var noState = ( f.stateProvince.options[f.stateProvince.selectedIndex].value == '' );

   		if ( usaSelected && noCity && noState )
		{
	   			setErrCode(f,21);
	   			return false;
		}

		if ( cntry == '' && noCity  && noState )
		{
	   			setErrCode(f,20);
	   			return false;
		}

     	return true;
}


//----------------------------------------------------
 // ok --> just go to success page
// !ok --> fill in "inputError" hidden field and go to error page
function proceed(f, path)
{
   // if city is "Enter city here" , blank it, since it does not make sense in a page by itself..
	//clearfield4();

  /* DBG(	'City= ' + f.city.value +
   			'-State= ' + f.stateProvince.options[ f.stateProvince.selectedIndex].value  +
			'-Country= ' + f.country.options[f.country.selectedIndex].value +
			'-Checkin= ' + f.arrivalDate.value +
			'-Checkout= ' + f.departureDate.value +
			'-lengthOfStay= ' + f.lengthOfStay.value +
			'-inputError= ' + f.inputError.value);*/

   f.action = path;
   return true;
}

//--------------------------------------------------------------------------------------------
				// M I S C
// -------------------------------------------------------------------------------------------

// if form has state pull down, set the country dynamically (US or CAN)
var us_states = [ "AL","AK","AP","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL",
	      		  "IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV",
	      		  "NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX",
	      		  "UT","VT","VA","WA","WI","WV", "WI","WY" ];
var ca_prov = [ "AB","BC","LB","MB","NB","NF","NWT","NS","NU","ON","PI","PQ","SK","YT" ];

// MISCELLANOUS: US TERRITORIES .IF they are in state drop-down, set the country to US..
// American Samoa (AS)
// Guam (GU)
// Federated States of Micronesia (FM)
// Marshall Islands (MH)
// Northern Marianas Islands (MP)
// Palau (PW)
// Puerto Rico (PR)
// Virgin Islands (VI)
var misc = [ "AS", "GU", "FM", "MH", "MP", "PW", "PR", "VI" ];

var fm = document.forms['SearchForm'];

if(fm.country != null)
{
	if( fm.stateProvince != null && fm.stateProvince.options != null )
			setOnChange( fm, fm.stateProvince );

}

// prevent form from being submitted more than once
	counter = 0;
	fm.onsubmit = function(){
        	counter++;
			//debugMsg = ( (counter > 1) ?  'Already submitted !' : 'Submitting..' );
			//alert(debugMsg);
        	return (counter > 1) ?  false : true;

			}


//--------------------------------------------------------------------------

// set an onchange evt hdler for a given state field from the first state value
// up to the number of states/prov ex : US ->53, CAN ->13

function setOnChange(fm, stateField )
{
		if( fm.country == null || stateField == null )
			return;

		stateField.onchange = function() { setCountry( fm, stateField ); }
		fm.country.onchange = function() { clearStateProv( stateField ); }

}

//----------------------------------------------------------------------------

// dynamically set the country given the state/Prov

function setCountry( fm, stateProv )
{
        if( stateProv == null || fm.country == null)
			return;

		var state = stateProv.options[stateProv.selectedIndex].value;

		if(  isIn(state, us_states) || isIn(state, misc) )
			setCountryValue('US');
		else if (  isIn(state, ca_prov) )
			setCountryValue('CA');
		else
			setCountryValue('');

}
//--------------------------------------------------

function isIn(elt, list)
{
	   if(elt == null || list == null)
	   		return false;

	   for( var ix =0; ix < list.length ; ix++)
	  		 if( list[ix] == elt )
			 {
				return true;
			 }

	   return false;
}

//---------------------------------------------------

function setCountryValue (val)
{
	if(fm.country == null)
			return;

	if( fm.country.options == null) // it is a txt field, most likely a hidden field.
		fm.country.value = val;
	else
	{
		for( var n =0; n < fm.country.options.length ; n++)
			if( fm.country.options[n].value == val )
			{
				fm.country.selectedIndex = n;
				break;
			}
	}
	DBG('country set to ' + val);
}

//----------------------------------------------------
// if country is not US/CA , clear the stateProv field
function clearStateProv(stateField)
{
	if(fm.country == null || fm.country.options == null || stateField == null)
			return;

	var cntry = fm.country.options[ fm.country.selectedIndex ].value ;
	if(cntry != 'US' || cntry != 'CA')
		stateField.selectedIndex = 0;
}

