/* Louis W. Adams, Jr.; May 15, 2009 */

window.onload = showDays;

function showDays() {
	var theDaysSpring = daysTill(4,24); /* Month and day for Spring Plant Sale. */
	var theDaysFall = daysTill(10,9);   /* Month and day for Fall Plant Sale.   */

    if (document.getElementsByTagName) {
    	var allTags = document.getElementsByTagName('span');
    }
    else {
        alert("Sorry.  The number of days until the next plant sale cannot be displayed.  Either the browser is using an old version of JavaScript that won't work here, or security software is blocking it.");
        return; /* Exit function. */    
    }
    	
	for (var i=0;i<allTags.length; i++) {
		if (allTags[i].className.indexOf("DaysTill") > -1) {
			allTags[i].innerHTML = showTheDaysTill(allTags[i].id);
		}
		if (allTags[i].className.indexOf("DaysTill2") > -1) {
			allTags[i].innerHTML = showTheSaleName(allTags[i].id);
		}
	}
	
    function showTheDaysTill(thisDate) {
        var theDays;
        switch(thisDate) {
			case "DayCount":
				
				/* Determine which sale is closest. */
				if (theDaysSpring < theDaysFall) {
                    theDays = theDaysSpring
                }
                else {
                    theDays = theDaysFall
                }
                
				break;
			default:
		}
		return theDays;
	}

	function showTheSaleName(thisDate) {
        var theName;
        switch(thisDate) {
			case "SaleName":
				
				/* Determine which sale is closest. */
				if (theDaysSpring < theDaysFall) {
                    theName="Spring "
                }
                else {
                    theName="Fall "
                }
                
				break;
			default:
		}
		return theName;
	}

	function daysTill(mm,dd) {
		var now = new Date();
		var inDate = new Date(now.getFullYear(),mm-1,dd);

        /* If date already passed, add one year to the date. */
		if (inDate.getTime() < now.getTime()) {
			inDate.setYear(now.getFullYear()+1);
		}

		return (Math.ceil(dayToDays(inDate) - dayToDays(now)));
	}

	function dayToDays(inTime) {
		return (inTime.getTime() / (1000 * 60 * 60 * 24)); /* Convert milliseconds into days. */
	}
}