var req

function alertDebug(message)
{
	if (debugMode ==1)
		alert(message)
}

function loadCities(objSel) 
{
	var regionCode
	
	// if region-enabled update, an empty region means clearing the city list
	if (document.forms[0].searchMode.value == "weekly" && objSel.selectedIndex == 0)
	{
		// an empty region means clearing the city list
		document.forms[0].cityZip.options.length = 0
	}
	else
	{
		// otherwise filter 
		regionCode = objSel.options[objSel.selectedIndex].value;
		
		// issue client request to update drop-down
		clientRequestingHandler()	
		
		//todo remove getCityList
		getCityList(regionCode)
	}
	
}

function getChannelId(searchMode)
{
	if (searchMode == "weekly")
		return 1
	else
		return 0
}

function testRAD(channelId)
{
	alertDebug("channelID:" +channelId)
	//index1.GetChannelCities(channelId)
}

function getCityList(regionCode)
{
	req = false;
	
	if (document.forms[0].searchMode.value == "weekly")
		channelId = 1
	else
		channelId = 0
	
	testRAD(channelId)
	
	url = "includes/getRegionCities.asp?channelID="+channelId+"&regionId=" +regionCode
	
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("MSXML2.ServerXMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send("");
	}
}

function processReqChange() 
{
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
            
            //alert(req.responseText)
            objResults = eval('(' +req.responseText +')')
            populateCitiesList(objResults);
        } else {
            alert("There was a problem retrieving the Data:\n" +
                req.statusText);
        }
    }
}

function populateCitiesList(cities)
{    
	var citiesList = document.getElementById("cityZip");
	var firstOptionText = "";

	//if we couldn't find the cities drop down
	if (citiesList == null)
	{
		return; //couldn't find the cities dropdown...
	}
	
	citiesList.options.length = 0; //reset the cities dropdown
	
	// add first entry into the list
	//alertDebug(document.forms[0].searchMode.value)
	with (document.forms[0])
	{
		if (searchMode.value == "nightly" || searchMode.value == "packages" || (searchMode.value == "weekly" && region.selectedIndex > 0))
		{
			firstOptionText = "Please Select a City"
		}
	}
	citiesList.options[citiesList.options.length] = new Option(firstOptionText, "");       
	
	//alert(cities)
	//alert("rows len:" +cities.Rows.length)
	for (var i = 0; i < cities.Rows.length; ++i)
	{
		citiesList.options[citiesList.options.length] = new Option(cities.Rows[i].state +" -- " +cities.Rows[i].city, cities.Rows[i].city +"--" +cities.Rows[i].zip);       
	}  
	
}

function dateDiff(date1, date2)
{
	var one_day=1000*60*60*24
	return Math.ceil((date1.getTime()-date2.getTime())/(one_day))
}

function dateAdd(indt, days) {
	var d = new Date(indt);
	var dv = d.valueOf();
	var ndv;

	ndv = dv + (days*(1000*60*60*24));
	
	var nd = new Date(ndv);
	return ((nd.getMonth() + 1) + "/" + nd.getDate() + "/" + nd.getFullYear());
}

function dateAddPrev(indt, days, sign) {
	var d = new Date(indt);
	var dv = d.valueOf();
	var ndv;
	if (sign == "+")
		ndv = dv + (days*(1000*60*60*24));
	else
		ndv = dv - (days*(1000*60*60*24));
	var nd = new Date(ndv);
	return ((nd.getMonth() + 1) + "/" + nd.getDate() + "/" + nd.getFullYear());
}

function setSelectValue(obj, value)
          {
			var i = 0
			foundText = false
			
			for (i = 0; i < obj.options.length; i++)
			{
				if (obj.options[i].value == value)
				{
					obj.selectedIndex = i
					foundText = true
					break
				}
			}
			
			if (!foundText)
				obj.options[0].selected
			
          }
          
          function setSelectText(obj, value)
          {
			var i = 0
			foundText = false
			
			//alert("-" +value +"-")
			for (i = 0; i < obj.options.length; i++)
			{
				if (obj.options[i].text == value)
				{
					obj.selectedIndex = i
					foundText = true
					break
				}
			}
			
			if (!foundText)
				obj.options[0].selected
			
          }
          
          
          function checkWeeklyDate()
          {
			with (document.forms.fineavail)
			{
				if (searchMode.value == "weekly")
					departdate = dateAdd(arrival.value, 7)
			}
          }
          
          function displayRegionFields(display)
          {
			alertDebug(autoComplete)
			alertDebug(display)
			if (autoComplete == 0)
			{
				// show the region drop-down
				document.getElementById("regionSelect").style.display = "inline"
				document.getElementById("regionSelect").style.visibility = "visible"
			}
			else	
			{
				// position form fields
				positionFormFields()
			}
			
			if (display)
			{
				
				document.getElementById("region").style.display = "inline"
				document.getElementById("region").style.visibility = "visible"
				
				// filter city list
				with (document.forms[0])
				{
					
					// if a region is selected
					if (region.selectedIndex > 0)
					{
						var regionCode
	
						regionCode = region.options[region.selectedIndex].value;
						//getCityList(regionCode)
					}
					else
					{
						// clear city list
						cityZip.options.length = 0
					}
					
				}
				
			}
			else
			{
				// hide the drop-down
				//regionSelect.style.display = 'none'
				document.getElementById("regionSelect").style.display = "none"
				
				with (document.forms[0])
				{	
					//alert("czsi:" +cityZip.selectedIndex)
					if (cityZip.selectedIndex > 0)
					{
						// get the current city
						varCity = cityZip.options[cityZip.selectedIndex].value	
						
						//alert("city:" +city)
						//alert("cityZip:" +varCity)	
					
						// load all the cities
						//getCityList('')
						//alert(cityZip.options.length)
						
						// set the drop-down city value
						setSelectValue(cityZip, varCity)
					}
					else
					{
						// load all the cities
						//getCityList('')
					}
				}
			}
          }
          
          
          function displayPackageAdditionalFields(display)
          {
			
			if (display)
			{
				document.getElementById("divGuests").style.display = "inline"
				//divGuests.style.display = 'inline'
			}
			else
			{
				document.getElementById("divGuests").style.display = "none"
				//divGuests.style.display = 'none'
			}
          }
          
          function validateCity()
          {
			alertDebug("validateCity")
			var valid = true
			
				with (document.forms[0])
				{
					//alertDebug(RadComboBox1_Input.value)
					//alert("ac:" +autoComplete)
					
					if (autoComplete == 1)
					{
					    combo = RadComboBox1
					
					    if (combo.GetValue() == "")
						    valid = false
    					
					    if (!valid)
					    {
						    if (searchMode.value == "nightly" || searchMode.value == "packages")
						    {
							    alert("Please Select City")
							    RadComboBox1_Input.focus()
							    return false
						    }
						    else
						    {
							    // weekly
							    // if autoComplete mode focus on city autocomplete
							    if (autoComplete == 1)
							    {
								    alert("Please Select City")
								    RadComboBox1_Input.focus()
								    return false
							    }
							    else
							    {
								    // otherwise on the region
								    alert("Region and City must be selected")
								    RadComboBox1_Input.focus()
								    return false
							    }
						    }
					    }
					}
				    else
				    {
				        // drop-down validation
				        if (cityZip.selectedIndex <= 0)
				        {
				            alert("Please Select City")
				            cityZip.focus()
				            valid = false
				        }
				        else
				            valid = true
				    }
				    
				}
				
				alertDebug("city validation:" +valid)
				return valid
          }
          
			
			function channelMileRound(miles)
			{
				if (miles <=5)
					{ miles = 5 }
				else if (miles <= 10)
					{ miles = 10 }
				else if (miles <= 25)
					{ miles = 25 }
				else if (miles <= 50)
					{ miles = 50 }
				else if (miles <= 100)
					{ miles = 100 }
				else if (miles <= 200)
					{ miles = 200 }
				else
					{ miles = 300 }
				
				return miles
			}
					
			
			function validateSearch()
			{
				alertDebug("validate")

				if (validateCity())
				{
					with (document.forms.fineavail)
					{
						// split the city zip value into the hidden form fields
						// in case of autocomplete get the values from the RadControl
						if (autoComplete == 1)
						{
						    //alertDebug("value:" +RadComboBox1_value.value)
						    arrCityZip = RadComboBox1_value.value.split("--")
						}
						else
						{
						    // otherwise get the data from the city drop-down
						    arrCityZip = cityZip.options[cityZip.selectedIndex].value.split("--");
						}
						
						city.value = Text.trim(arrCityZip[0])
						if (arrCityZip.length > 1)
							zip.value = Text.trim(arrCityZip[1])
						
						
						// validate arrival and departdate are not empty
						if (document.getElementById("arrival").value.length == 0)
						{
						    alert("Please enter arrival date")
						    document.getElementById("arrival").focus()
						    return false;
						}
						
						if (document.getElementById("departdate").value.length == 0)
						{
						    alert("Please enter departure date")
						    document.getElementById("departdate").focus()
						    return false;
						}
						
						
						startdate = new Date(document.getElementById("arrival").value);
						enddate = new Date(document.getElementById("departdate").value);
						
						
						
						var today = new Date();
						
						//miles = document.getElementById("maxmiles").value
						miles = maxmiles.value
						
						if (miles == "" || isNaN(miles))
						{
							alert("Please enter in a valid mile(s)");
							return false;
						}
						
						//if (occupants == "")
						//{
						//	alert("Please choose a valid occupant number")
						//	return false;
						//}
						
						if (startdate >= enddate)
						{
							alert("The arrival date can not be greater than the depart date");
							return false;
						}
						
						if (enddate < today)
						{
							alert("The depart date can not be less than today's date");
							return false;
						}
						

						if (searchMode.value == "weekly" )
						{
							if( dateDiff(startdate, today) < 3)
							{
								alert("The arrival date must be at least 3 days from today.");
								return false;
							}
						}
						else
						{
							if (dateDiff(today, startdate) > 1)
							{
								alert("The arrival date can not be less than today's date");
								return false;
							}
						}	
						
						
						// if search type is weekly 
						if (searchMode.value == "weekly")
						{
							// round up miles
							miles = channelMileRound(miles)
							//alert(miles)
							
							// then min stay is 7 and max stay is 20
							if (dateDiff(enddate, startdate) < 7)
							{
								alert("The date span can not be less than 7 days");
								return false;
							}
							
							if (dateDiff(enddate, startdate) > 21)
							{
								alert("The date span can not be more than 21 days");
								return false;
							}
						}
						else
						{
							// otherwise is min 1 day and max 60
							if (dateDiff(enddate, startdate) > 60)
							{
								alert("The date span can not be more than 60 days");
								return false;
							}
						}
			
						maxmiles.value = miles
					
						resort = ""
						alertDebug(arrival.value)
						alertDebug(departdate.value)
						alertDebug(miles)
						alertDebug(resort)
						alertDebug(city.value)
						alertDebug(zip.value)
						alertDebug(searchMode.value)
						reg=""
						
						if (searchMode.value == "weekly")
						{
							alertDebug("try region")
							reg = region.options[region.selectedIndex].value
						}		
						alertDebug("region" +reg)
					
						alertDebug("post 1")
						
						var url = "reservations/searching.asp"
						+ "?arrival=" + escape(arrival.value)
						+ "&departdate=" + escape(departdate.value)
						+ "&maxmiles=" + escape(miles)
						+ "&occupants=" + "0"
						+ "&resortid=" + escape(resort)
						+ "&city=" + escape(city.value)
						+ "&zip=" + escape(zip.value)
						+ "&mode=city"
						+ "&region=" +escape(reg)
						+ "&searchMode=" +escape(searchMode.value)
						+ "&searchRequestPage=" +escape(SearchRequestPage.value)
					
						alertDebug("validation complete")
						alertDebug(url)
					}
					
					window.location = url;
				
					return false;	
				}
				else
					return false;
					
			}