// File: index_promo.js
// Description:
// Creator: David F. Kersting 
// Updated by: Militska Gomez
// Current Version:  1.0
// History:
// Version: 1.0  Date: 07.01.2003  
// Comments: Modified for Promo Search Home 2

// 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( ! okPromoLocation(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 okPromoLocation(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' || f.city.value == 'City');
		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;
   if (f.lengthOfStay != null) f.lengthOfStay.disabled = false; 
   if (f.departureDateMonth != null) f.departureDateMonth.disabled = false; 
   if (f.departureDateDay != null) f.departureDateDay.disabled = false; 
   if (f.departureDateYear != null) f.departureDateYear.disabled = false; 
   f.submit();
   return false;
}

//--------------------------------------------------------------------------------------------
				// 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","NL","NWT","NS","NU","ON","PI","PE","QC","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 au_prov = [ "ACT","NSW","NT","QNL","SA","TS","VC","WA" ]
var mex_prov = [ "AQS","BCN","BCS","CM","CP","CUA","CH","CL","DG","EM","GJ","GR","HD","JL","MC",
				 "MCN","MR","NT","NL","OX","PB","QRT","QR","SIP","SL","SN","TL","TB","TM","VC","YC","ZC" ]

var fm = document.forms['SearchForm'];
 
if(fm.country != null)
{	
	if( fm.stateProvince != null && fm.stateProvince.options != null ) 
			setPromoOnChange( 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 setPromoOnChange(fm, stateField )
{
		if( fm.country == null || stateField == null )
			return;
	
		stateField.onchange = function() { setPromoCountry( fm, stateField ); }
		fm.country.onchange = function() { clearStateProv( stateField ); }
	
}

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

// dynamically set the country given the state/Prov

function setPromoCountry( fm, stateProv )
{
        if( stateProv == null || fm.country == null)
			return;
	
		var state = stateProv.options[stateProv.selectedIndex].value;
			
		if(  isIn(state, us_states) || isIn(state, misc) ) 
			setPromoCountryValue('US');
		else if (  isIn(state, ca_prov) )
			setPromoCountryValue('CA');
		else if (isIn(state, au_prov))
			setPromoCountryValue('AU');
		else if (isIn(state, mex_prov))
			setPromoCountryValue('MX');
		else 
			setPromoCountryValue('');
			 
}
//--------------------------------------------------

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 setPromoCountryValue (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;
}
