/* returns true if form is valid.  shows alert and returns false if not
 *
 * @param Form frm the form object to be validated
 * @returns boolean true if form is valid
 */
function checkForm(frm)
{
	/* 9/4/08/JS Not needed, we don't pick # here anymore.
    if (frm.NumberAdult.value + frm.NumberChild.value == 0)
    {
        alert('Please specify at least one adult or child skier');
        return false;
    }
	*/

    if (frm.StartDate.value == '')
    {
        alert('Please specify the start date of your ski trip');
        return false;
    }
    
    // check that the date seems to be valid
	//if( frm.StartDate.value.match(/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{4}/gi) ) 
	if (isDate(frm.StartDate.value))
	{
		
		datesList = frm.StartDate.value.split(/[\/\-]/);
		y = datesList[2];
		m = datesList[0] - 1;
		d = datesList[1];

		trip_date = new Date();
		trip_date.setDate(d);
		trip_date.setMonth(m);
		trip_date.setFullYear(y);
		
		today = new Date();
		
		if (compareDates(today, trip_date) < 1) 
		{
			alert('Please choose a start date after today.');
			return false;
		}

		
	} else {
	
		alert('Please specify a valid start date for your trip, formatted as MM/DD/YYYY');
		return false;
	
	}
    
    /*
    if (frm.ResortGroup.options)
    {
        // main search has resort dropdown
        if (frm.ResortGroup.options[frm.ResortGroup.selectedIndex].value != 0)
        {
            // this is a resort-specific search
            frm.action = 'resort_detail.php';
        }
    }
    else
    {
        // modify search has hidden field
        if (frm.ResortGroup.value != 0)
        {
            // this is a resort-specific search
            frm.action = 'resort_detail.php';
        }
    }
    */
    
    return true;
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}


 
/* results ready to display
 */
function displayResults() 
{
    // main search has resort dropdown
    /*
    if (document.forms[0].ResortGroup.value != 0)
    {
        // this is a resort-specific search
        document.forms[0].action = 'resort_detail.php';
    }
    */
    
    document.forms[0].submit();
}

/* allow back-end to locate tickets
 */
function processSearch()
{
    setTimeout('displayResults()', 1000);
}


/* compares two given javascript date objects
 *
 * @param date date1
 * @param date date2
 * @return int -1 if date1 > date2 || 0 if dates are equal || 1 if date1 < date2
 */
function compareDates(date1, date2) {

	var year1 = date1.getYear();
	var year2 = date2.getYear();
	var month1 = date1.getMonth();
	var month2 = date2.getMonth();
	var day1 = date1.getDate();
	var day2 = date2.getDate();

	if (year1 > year2) {
		return -1;
	}
	if (year2 > year1) {
		return 1;
	}

	//years are equal
	if (month1 > month2) {
		return -1;
	}
	if (month2 > month1) {
		return 1;
	}

	//years and months are equal
	if (day1 > day2) {
		return -1;
	}
	if (day2 > day1) {
		return 1;
	}

	//days are equal
	return 0;

}


// global var so the readystate has access to it
var reloadResortListForm;

function reloadResortList(frm)
{
    // build the url for the ajax post
    url = '/index_js.php?RegionCatId=' + frm.RegionCatId.value;
    
    // set the global var so onreadystate has scope without having to hunt it down
    reloadResortListForm = frm;
    
    // start the request
    startRequest(url, onResortReadyStatusChange)
}


function startRequest(url, readyStateHandler) 
{

	req = false;
    if(window.XMLHttpRequest) 
    {
        // native XMLHttpRequest object
    	try 
    	{
			req = new XMLHttpRequest();
        } 
        catch(e) 
        {
			req = false;
        }
    } 
    else if(window.ActiveXObject) 
    {
        // IE/Windows ActiveX version
       	try 
       	{
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} 
      	catch(e) 
      	{
        	try 
        	{
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} 
        	catch(e) 
        	{
          		req = false;
        	}
		}
    }
    
	if(req) 
	{
		req.onreadystatechange = readyStateHandler;
		req.open("GET", url, true);
		req.send("");
	}
	else
	{
        appendStatus('Browser does not support HTTP_POST', false, true);
	}
}

function onResortReadyStatusChange() 
{
    // only if req shows "loaded"
    if(req.readyState == 1) 
    { 
        showStatus("Loading...", true, false);
        return;
    } 
    
    if (req.readyState == 4) 
    {
        // make sure status is ok
        if (req.status != 200) 
        {
             appendStatus('Unable to connect to server. Status ' + req.status + ': ' + req.statusText, false, true);
             return;
       }
        
        resorts = null;
        
        // index_js returns JSON.  try to parse it
        try
        {
            resorts = JSON.parse(req.responseText);
        }
        catch(e)
        {
            appendStatus('Error parsing JSON response', false, true);
            return;
        }
        
        // check if index_js returned a JSONError
        if (resorts.name == 'JSONError')
        {
            appendStatus('Unexpected results: ' + resorts.message, false, true);
            return;
        }

        // everything looks good.  rebuild the dropdown list
        selected = '';
        if (reloadResortListForm.RegionCatId.options[reloadResortListForm.RegionCatId.selectedIndex].value != 'X_0')
        {
            selected = trim(reloadResortListForm.RegionCatId.options[reloadResortListForm.RegionCatId.selectedIndex].text);
        }
        reloadResortListForm.ResortGroup.options.length = 0;
        reloadResortListForm.ResortGroup.options[0] = new Option('All ' + selected + ' Resorts', '', true, false);
        
        for (i = 0; i < resorts.length; i++)
        {
            reloadResortListForm.ResortGroup.options[i+1] = new Option(resorts[i].ResortGroup, resorts[i].ResortGroup, true, false);
        }
        
        hideStatus();

    }
		
}

function trim(str)
{
    // replace null at the beginning of string.  IE thinks &nbsp; is a null character
    while (Asc(str.substr(0,1)) == 0 && str.length > 1)
    {
        str = str.substr(1);
    }

   return str.replace(/^\s*|\s*$/g,"");
}

function Asc(string)
{
	var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@";
	var loAZ = "abcdefghijklmnopqrstuvwxyz";
	symbols += loAZ.toUpperCase();
	symbols += "[\\]^_`";
	symbols += loAZ;
	symbols += "{|}~";
	var loc;
	loc = symbols.indexOf(string);
	if (loc > -1)
	{ 
		Ascii_Decimal = 32 + loc;
		return (32 + loc);
	}
	return (0);
}

var persisted = false;

function showStatus(msg, show_animation, persist)
{
    reloadResortListForm.ResortGroup.options.length = 0;
    reloadResortListForm.ResortGroup.options[0] = new Option(msg, '0', true, false);
    reloadResortListForm.ResortGroup.options[1] = new Option('All Resorts', '0', true, false);
    return false;
    
    /*
    if (msg == '')
    {
        hideStatus();
    }
    else
    {
        
        if (show_animation)
        {
        document.getElementById('status').innerHTML = '';
        }
        else
        {
        document.getElementById('status').innerHTML = '';
        }
        
        document.getElementById('status').innerHTML += msg;
        
        if (persist)
        {
            document.getElementById('status').innerHTML += "<div><input type=\"button\" value=\"  OK  \" onclick=\"persisted = false; document.getElementById('status').style.display = 'none'; return false;\"></div>";
            persisted = true;
        }
    }
    */
}

function appendStatus(msg, show_animation, persist)
{
    // msg = document.getElementById('status').innerHTML + msg;
    showStatus(msg, show_animation, persist);
}

function hideStatus()
{
    /*
    if (!persisted)
    {
        document.getElementById('status').style.className = 'searchLabel';
        document.getElementById('status').innerHTML = 'SELECT A RESORT';
    }
    */
}

