$(document).ready(function(){
  
    // an array of Years is listed in the primary driver
    // this function takes a year and an array of years
    // returns true of the year exists within the array
    // else false
    // ** could make array global, opted to keep it 'private'
    // by making local since this isn't an OOP design.
    function verifyYear (_Year, yearArray) {
    
    	for (index in yearArray) {
    	  if (yearArray[index] == _Year) return true;
    	  
    	}
    	return false;
    	
    }
    
    // Checks to see if leap year
    // returns true/false
    function isLeapYear(_Year) {
    
    	if (_Year % 400 == 0) 
    		return true;
        else if (_Year % 100 == 0)
        	return false;
    	else if (_Year % 4 == 0)
    		return true;
        else
         	return false;
    }
    
    // checks to see Month and Day selection are compatible 
    // i.e. 30 days in June or 31 Days in July.
    // cases correspond to month number - 1 = Jan, 12 = Dec
    // First checks if day is less than zero
    function verifyDateSelection(_Month, _Day) {
    
    	if (_Day <= 0) return false;
    
    	switch (_Month) {
    		case '4':
    		case '6':
    		case '9':
    		case '11':
      			if (_Day <= 30) return true;
      			else return false;
    		case '1':
    		case '3':
    		case '5':
    		case '7':
    		case '8':
    		case '10':
    		case '12':
      			if (_Day <= 31) return true
      			else return false;
    		case '2':
    			if (isLeapYear(_Year) && _Day <= 29)
    				return true;
    			else {
    				if (_Day <= 28) return true;
    				else return false;
    			}
    		default: alert('Invalid');
    	}
    	
    }
    
    // primary driver of the script
    // is called on submit of the form
    // calls the helper functions
    // returns true if success or false + alert
    $('#formName').submit(function () {
        var url;
    	var success = false;
    	var Month = $('select#month').val();
    	var Day   = $('select#day').val();
   	 	var Year  = $('select#year').val();
    	var yearArray = new Array(2011, 2012, 2013, 2014, 2015);
    	

    	if (verifyYear(Year, yearArray)) {
    	
    		if(verifyDateSelection(Month, Day)) {

    			success = true;
    		}
    		else success = false;
    	}
    	else {
    		success = false;
    	}
    	
    	if (success)  {
    	
    	   url = "http://availabilityonline.com/availtable.asp?yearselect=" + Year + "&monthselect=" + Month + "&dayselect=" + Day + "&un=innweston&show_only=&show_only_mode_view_all_button=&show_only_mode_view_all_button_toggle=&submit2=Ahead+14+Days";
    	   
    	   $('#formName').attr('action', url);
    	
    		return true;
    	}
    		
    });
});
