/*
	Name			: /tools/sobriety.js
	Author			: Frank Marion
	Created			: Saturday, June 23, 2007; 12:39 PM
	Last Updated	: Wednesday, June 27, 2007; 11:58 AM
	History			: Creation.
	Purpose			: 1) Create a form that a user may enter a day to calculate the time span of sobriety expressed in
					  years, months, weeks, days.
					  2) Display random strings of text to serve as "motivational messages

	Credits			: calcTimeSpan source is based on http://snippets.dzone.com/posts/show/623

*/


/* ------------------------------------- User Settings ------------------------------------- */

// HTML structure: H1
var html_head1_id = 'html_head1';
var html_h1_txt_str = 'Big Book Recovery Calculator';

// HTML structure: P description 01
var html_p1_desc = 'html_p1_desc';
var html_p1_desc_txt_str = 'Use this sobriety or clean date calculator to determine how long you have been clean and sober.';

// HTML structure: P description 02
var html_p2_desc = 'html_p2_desc';
var html_p2_desc_txt_str = 'Enter the numeric year, month, day you stopped drinking or using.';

// The text description to put above the random quotes
var text_above_random = 'How can I recover from a seemingly hopeless state of mind and body? The answers can be found in the first 164 pages (4th Edition) of the Big Book of Alcoholics Anonymous:';

// Text that precedes the time span display
var time_msg = 'You have been clean or sober for '; // You have been clean for X years, X Months, X days....

// Create an array of lines of random text. Remember that all ' within single quotes must be preceded with a slash, as such: \'
var r_quote = new Array();
r_quote[0]='Page 14:  paragraph 7: For if an alcoholic (addict) failed to perfect and enlarge his spiritual life through work and self-sacrifice for others, he could not survive the certain trials and low spots ahead.';
r_quote[1]='Page 20, paragraph 1:  Our very lives, as ex-problem drinkers (addicts), depend upon our constant thought of others and how we may help meet their needs.';
r_quote[2]='Page 102, paragraph 1:  But if you are shaky you had better work with another alcoholic (addict) instead.';
r_quote[3]='Page 97, paragraph 2:  Helping others is the foundation stone of your recovery. A kindly act once in a while isn\'t enough. (p. 97, A.A. 4th Edition) ';
r_quote[4]='Page 84, paragraph 3:  There is action and more action. Faith without works is dead.';
r_quote[5]='Page 84, paragraph 3:  We have entered the world of the Spirit. Our next function is to grow in understanding and effectiveness.* This is not an overnight matter. It should continue for our lifetime.';
r_quote[6]='Page 84, paragraph 3:  Then we resolutely turn our thoughts to someone we can help. Love and tolerance of others is our code.';
r_quote[7]='Page 89, paragraph 1:  Practical experience shows that nothing will so much insure immunity from drinking as intensive work with other alcoholics. It works when other activities fail. This is our twelfth suggestion: Carry this message to other alcoholics! You can help when no one else can. You can secure their confidence when others fail.';
r_quote[8]='Page 15, paragraph 2:  I was not too well at the time, and was plagued with waves of self-pity and resentment. This sometimes nearly drove me back to drink, but I soon found that when all other measures failed, working with another alcoholic would save the day. Many times I have gone to my old hospital in despair. On talking to a man there, I would be amazingly lifted up and set on my feet. It is a design for living that works in rough going.';
r_quote[9]='Page 19, paragraph 1:  The elimination of drinking is but a beginning. A much more important demonstration of our principles lies before us in our respective homes, occupations and affairs.';
r_quote[10]='Page xiii, paragraph 1:  To show other alcoholics precisely how we have recovered is the main purpose of this book.';
r_quote[11]='Page 59 paragraph 2:  Half measures availed us nothing.';
r_quote[12]='Page 84 paragraph 3:  We vigorously commenced this way of living, as we cleaned up the past.';
r_quote[13]='Page 58 paragraph 1:  ...a manner of living which requires rigorous honesty.';
r_quote[14]='Page 58 paragraph 2:  If you have decided you want what we have and are willing to go to any lengths to get it--then you are ready to take certain steps.';
r_quote[15]='Page 58 paragraph 3:  We thought we could find an easier, softer way. But we could not. With all the earnestness at our command, we beg of you to be fearless and thorough from the very start.';
r_quote[16]='Page 14, paragraph 2:  Simple, but not easy; a price had to be paid. It meant the destruction of self-centeredness.';
r_quote[17]='Page 132, paragraph 3:  We have recovered, and have been given the power to help others.';
r_quote[18]='Page 79, paragraph 2:  Reminding ourselves that we have decided to go to any lengths to find a spiritual experience, we ask that we be given strength and direction to do the right thing, no matter what the personal consequences might be.';
r_quote[19]='Page 45: paragraph: 2:  Lack of power, that was our dilemma. We had to find a Power by which we could live, and it had to be a Power greater than ourselves.';
r_quote[20]='Page 86, paragraph 4:  We may not be able to determine which course to take. Here we ask God for inspiration, an intuitive thought or a decision.';
r_quote[21]='Page 64, paragraph 1:  Though our decision was a vital and crucial step, it could have little permanent effect unless at once followed by a strenuous effort to face, and to be rid of, the things in ourselves which had been blocking us';
r_quote[22]='Page 85, paragraph 2:  It is easy to let up on the spiritual program of action and rest on our laurels. We are headed for trouble if we do, for alcohol is a subtle foe. We are not cured of alcoholism. What we really have is a daily reprieve contingent on the maintenance of our spiritual condition. Every day is a day when we must carry the vision of God\'s will into all of our activities. "How can I best serve Thee, Thy will (not mine) be done." These are thoughts which must go with us constantly. We can exercise our will power along this line all we wish. It is the proper use of the will.';
r_quote[23]='Page 99, paragraph 2:  we must try to repair the damage immediately lest we pay the penalty by a spree.';
r_quote[24]='Page 83, paragraph 1:  Yes, there is a long period of reconstruction ahead. We must take the lead.';
r_quote[25]='Page 74, paragraph 2:  The rule is we must be hard on our self, but always considerate of others.';
r_quote[26]='Page 85, paragraph 3:  But we must go further and that means more action.';
r_quote[27]='Page 85, paragraph 2:  Every day is a day when we must carry the vision of God\'s will into all of our activities.';
r_quote[28]='Page 80, paragraph 1:  If we have obtained permission, have consulted with others, asked God to help and the drastic step is indicated we must not shrink.';
r_quote[29]='Page 14, paragraph 2:  I must turn in all things to the Father of Light who presides over us all.';
r_quote[30]='Page 62, paragraph 3:  Above everything, we alcoholics must be rid of this selfishness. We must, or it kills us!';
r_quote[31]='Page 89, paragraph 2:  To watch people recover, to see them help others, to watch loneliness vanish, to see a fellowship grow up about you, to have a host of friends - this is an experience you must not miss.';
r_quote[32]='Page 33, paragraph 3:  If we are planning to stop drinking, there must be no reservation of any kind.';
r_quote[33]='Page 79, paragraph 2:  We must not shrink at anything.';
r_quote[34]='Page 86, paragraph 2:  But we must be careful not to drift into worry, remorse or morbid reflection, for that would diminish our usefulness to others.';
r_quote[35]='Page 120, paragraph 2:  we must redouble our spiritual activities if he expects to survive.';
r_quote[36]='Page 95, paragraph 3:  If we are to find God, the desire must come from within.';
r_quote[37]='Page 159, paragraph 3:  Though they knew they must help other alcoholics if they would remain sober, that motive became secondary.';
r_quote[38]='Page 156, paragraph 3:  Both saw that they must keep spiritually active.';
r_quote[39]='Page 143, paragraph 2:  we should understand that we must undergo a change of heart';
r_quote[40]='Page 69, paragraph 4:  Whatever our ideal turns out to be, we must be willing to grow toward it.';
r_quote[41]='Page 69, paragraph 4:  We must be willing to make amends where we have done harm.';
r_quote[42]='Page 44, paragraph 3:  we had to face the fact that we must find a spiritual basis of life - or else.';
r_quote[43]='Page 78, paragraph 3:  We must lose our fear of creditors no matter how far we have to go, for we are liable to drink if we are afraid to face them.';
r_quote[44]='Page 93, paragraph 3:  To be vital, faith must be accompanied by self sacrifice and unselfish, constructive action.';
r_quote[45]='Page 43, paragraph 4:  Our defense must come from a Higher Power.';
r_quote[46]='Page 66, paragraph 4:  We saw that these resentments must be mastered.';
r_quote[47]='Page 73, paragraph 5:  We must be entirely honest with somebody if we expect to live long or happily in this world.';
r_quote[48]='Page 164, paragraph 4:  Abandon yourself to God as you understand God. Admit your faults to Him and to your fellows. Clear away the wreckage of your past. Give freely of what you find and join us.';
r_quote[49]='Page xvi, paragraph 1:  This seemed to prove that one alcoholic (addict) could affect another as no nonalcoholic could. It also indicated that strenuous work, one alcoholic (addict) with another, was vital to permanent recovery.';
r_quote[50]='Page xvii, paragraph 1:  ...we were convinced of the need for moral inventory, confession of personality defects, restitution to those harmed, helpfulness to others, and the necessity of belief in and dependence upon God.';
r_quote[51]='Page xxii, paragraph 4:  ...recovery begins when one alcoholic (addict) talks with another alcoholic (addict), sharing experience, strength, and hope';
r_quote[51]='Page xxv, paragraph 4:  As part of his rehabilitation he commenced to present his conceptions to other alcoholics (addicts), impressing upon them that they must do likewise with still others.';
r_quote[52]='Page 59:  Step 1.  We admitted we were powerless over our addictions - that our lives had become unmanageable.';
r_quote[53]='Page 59:  Step 2. Came to believe that a Power greater than ourselves could restore us to sanity.';
r_quote[54]='Page 59:  Step 3. Made a decision to turn out will and our lives over to the care of God as we understood Him.';
r_quote[55]='Page 59:  Step 4. Made a searching and fearless moral inventory of ourselves.';
r_quote[56]='Page 59:  Step 5. Admitted to God, to ourselves, and to another human being the exact nature of our wrongs.';
r_quote[57]='Page 59:  Step 6. Were entirely ready to have God remove all these defects of character.';
r_quote[58]='Page 59:  Step 7. Humbly asked Him to remove our shortcomings.';
r_quote[59]='Page 59:  Step 8. Made a list of all persons we had harmed, and became willing to make amends to them all.';
r_quote[60]='Page 59:  Step 9. Made direct amends to such people wherever possible, except when to do so would injure them or others.';
r_quote[61]='Page 59:  Step 10. Continued to take personal inventory and when we were wrong promptly admitted it.';
r_quote[62]='Page 59:  Step 11. Sought through prayer and meditation to improve our conscious contact with God as we understood Him, praying only for knowledge of His will for us and the power to carry that out.';
r_quote[63]='Page 60:  Step 12. Having had a spiritual awakening as the result of these steps, we tried to carry this message to addicts, and to practice these principles in all our affairs.';
r_quote[64]='Page 53, paragraph 3:  God is everything or he is nothing. God either is or he isn\'t. What was our choice to be?';
r_quote[65]='Page 63, paragraph 2: Step 3 Prayer - God, I offer myself to Thee - to build with me and do with me as Thou wilt. Relieve me of the bondage of self, that I may better do Thy will. Take away my difficulties, that victory over them may bear witness to those I would help of Thy Power, Thy Love and Thy Way of Life. May I do Thy will always!';
r_quote[66]='Page 67, paragraph 1: Forgiveness Prayer - We asked God to help us show them the same tolerance, pity, and patience that we would cheerfully grant a sick friend. When a person offended we said to ourselves, "This is a sick man. How can I be helpful to him? God save me from being angry. Thy will be done.';
r_quote[67]='Page 68, paragraph 4:  We ask Him to remove our fear and direct our attention to what He would have us be.';
r_quote[68]='Page 69, paragraph 3:  We asked God to mold our ideals and help us live up to them.';
r_quote[69]='Page 69, paragraph 4:  In meditation, we ask God what we do about each specific matter.';
r_quote[70]='Page 70, paragraph 3:  To sum up about sex: We pray for the right ideal, for guidance in each questionable situation, for sanity and for strength to do the right thing.';
r_quote[71]='Page 76, paragraph 1:  If we still cling to something we will not let go, we ask God to help us be willing.';
r_quote[72]='Page 76, paragraph 2:  Step 7 Prayer - My Creator, I am now willing that You should have all of me, good and bad. I pray that You now remove from me every single defect of character which stands in the way of my usefulness to you and my fellows. Grant me strength, as I go out from here, to do Your bidding. Amen';
r_quote[73]='Page 76, paragraph 3:  Making Amends - If we haven\'t the will to do this, we ask until it comes.';
r_quote[74]='Page 79, paragraph 2:  Legal Matters - We ask that we be given strength and direction to do the right thing, no matter what the personal consequences might be.';
r_quote[75]='Page 83, paragraph 1:  So we clean house with the family, asking each morning in meditation that our Creator show us the way of patience, tolerance, kindliness and love.';
r_quote[76]='Page 84, paragraph 3:  Continue to watch for selfishness, dishonesty, resentment and fear. When these crop up, we ask God at once to remove them.';
r_quote[77]='Page 86, paragraph 2:  After meditation on the day just completed, We ask God\'s forgiveness and inquire what corrective measures should be taken.';
r_quote[78]='Page 86, paragraph 3:  Before we begin our day, we ask god to direct our thinking, especially asking that it be divorced from self-pity, dishonest or self-seeking motives.';
r_quote[79]='Page 86, paragraph 4:  We may not be able to determine which course to take. Here we ask God for inspiration, an intuitive thought or a decision.';
r_quote[80]='Page 87, paragraph 2:  We usually conclude the period of mediation with a prayer that we be shown all through the day what our next step is to be, that we be given whatever we need to take care of such problems. We especially ask for freedom from self-will, and are careful to make no requests for ourselves only We may ask for ourselves, however, if others will be helped. We are careful never to pray for our own selfish ends.';
r_quote[81]='Page 87, paragraph 4:  As we go through the day we pause, when agitated or doubtful, and ask for the right thought or action.';
r_quote[81]='Page 102, paragraph 3:  Your job now is to be at the place where you may be of maximum helpfulness to others, so never hesitate to go anywhere if you can be helpful. You should not hesitate to visit the most sordid spot on earth on such an errand. Keep on the firing line of life with these motives and God will keep you unharmed. ';
// Colour to indicate error
var strErrColour = 'salmon';

/* ----------------------------- DO NOT EDIT BEYOND THIS POINT ----------------------------- */





/* --------------------------------------- Utilities --------------------------------------- */


// General usage date
var Now = new Date();

// Determine the 'physical location' of this script in the page
var thisScriptLocation = document.getElementById('sc').parentNode;

// Trim text
function trim(arg) {
	if (arg.length > 0) {
		return arg.replace(/^\s+|\s+$/, '');
	} else {
		return null;
	}
}

// Extract a year from inputted date
function getThisYear(arg){
	x = arg.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return parseInt(y);
}

// Clears background of field with error style active
function clearField(obj) {
	if (obj) {
		obj.style.backgroundColor = '';
	}
}

/* --------------------------------- Random quote  --------------------------------------------- */

// Get a random number
function getRandom() {
    var random_number = Math.floor(Math.random() * r_quote.length);
    return random_number;
}
// Select a quote from the array based on the random number
function randomQuote() {
	var get_quote=getRandom();
	return r_quote[get_quote];
}

/* ----------------------------- Create the HTML Structure ---------------------------------- */

// This is the sucker that make the whole HTML structure
function buildHTMLStructure() {

	// HTML structure: DIV. Containing div
	dv = document.createElement("div");
	dv.setAttribute("id", 'html_container_div');
	dv.style.padding = '10px';
	dv.style.border = '1px solid black';

	// HTML structure: H1. Intro
	head1 = document.createElement("h1");
	head1.setAttribute("id",html_head1_id);
	head1_txt = document.createTextNode(html_h1_txt_str);

	// HTML structure: P. description 01
	html_p1_desc = document.createElement("p");
	html_p1_desc.setAttribute("id",'html_p1_desc');
	html_p1_desc_txt = document.createTextNode(html_p1_desc_txt_str);

	// HTML structure: P. description 02
	html_p2_desc = document.createElement("p");
	html_p2_desc.setAttribute("id",'html_p2_desc');
	html_p2_desc_txt = document.createTextNode(html_p2_desc_txt_str);

	// HTML structure: P. Wraps form
	html_p_form = document.createElement("p");
	html_p_form.setAttribute("id", 'html_p_form');
	html_p_form.style.padding = '10px';
	html_p_form.style.textAlign = 'center';

	// HTML structure: FORM. It's the form. Can it be any more obvious?
	f = document.createElement("form");
	f.action = this.location.href;
	f.method = "POST";

	// HTML structure: INPUT. Year input.
	iptYear = document.createElement("input");
	iptYear.setAttribute("type","text");
	iptYear.setAttribute("name",'form_field_year');
	iptYear.setAttribute("id",'form_field_year');
	iptYear.setAttribute("value",Now.getFullYear());
	iptYear.setAttribute("size","4");
	iptYear.setAttribute("maxlength","4");
	iptYear.style.margin = '2px';
	iptYear.onclick = function(){clearField(this);}


	// HTML structure: INPUT. Month input.
	iptMonth = document.createElement("input");
	iptMonth.setAttribute("type","text");
	iptMonth.setAttribute("name",'form_field_month');
	iptMonth.setAttribute("id",'form_field_month');
	iptMonth.setAttribute("value",Now.getMonth()+1);
	iptMonth.setAttribute("size","2");
	iptMonth.setAttribute("maxlength","2");
	iptMonth.style.margin = '2px'
	iptMonth.onclick = function(){clearField(this);}

	// HTML structure: INPUT. Date input.
	iptDate = document.createElement("input");
	iptDate.setAttribute("type","text");
	iptDate.setAttribute("name",'form_field_date');
	iptDate.setAttribute("id",'form_field_date');
	iptDate.setAttribute("value",Now.getDate());
	iptDate.setAttribute("size","2");
	iptDate.setAttribute("maxlength","2");
	iptDate.style.margin = '2px';
	iptDate.onclick = function(){clearField(this);}


	// HTML structure: INPUT. Button input.
	subm = document.createElement("input");
	subm.setAttribute("type","button");
	subm.setAttribute("name","button");
	subm.setAttribute("value","Submit");
	subm.style.margin = '2px';
	subm.setAttribute("onClick","dateValidation();");
	subm.onclick = dateValidation;

	// HTML structure: P. Display time span messages.
	html_p_time_span = document.createElement("p");
	html_p_time_span.setAttribute("id",'html_p_time_span');
	html_p_time_span.style.fontWeight = 'bold';
	html_p_time_span_txt = document.createTextNode('');

	// HTML structure: P. Display explaining the quotes
	html_p_explain_quote = document.createElement("p");
	html_p_explain_quote.setAttribute("id",'html_p_explain_quote');
	html_p_explain_quote.style.fontSize = '.85em';
	html_p_explain_quote_txt = document.createTextNode(text_above_random);

	// HTML structure: P. Display random quotes
	html_p_random_quote = document.createElement("p");
	html_p_random_quote.setAttribute("id",'html_p_random_quote');
	html_p_random_quote_txt = document.createTextNode('');

// Now put it all together

	// DIV: container div at 'physical location' of tag script
	thisScriptLocation.appendChild(dv);
	
	// H1: Introductory H1
	dv.appendChild(head1);
	head1.appendChild(head1_txt);
	
	// P: First descriptive paragraph
	dv.appendChild(html_p1_desc);
	html_p1_desc.appendChild(html_p1_desc_txt);

	// P: Second descriptive paragraph
	dv.appendChild(html_p2_desc);
	html_p2_desc.appendChild(html_p2_desc_txt);

	// P: P that wraps form
	dv.appendChild(html_p_form);

	// FORM: append the form
	html_p_form.appendChild(f);

	// INPUT: the form elements
	f.appendChild(iptYear);
	f.appendChild(iptMonth);
	f.appendChild(iptDate);
	f.appendChild(subm);

	// P: the form elements
	dv.appendChild(html_p_time_span);
	html_p_time_span.appendChild(html_p_time_span_txt);

	// P: the paragraph ABOVE the random quote
	dv.appendChild(html_p_explain_quote);
	html_p_explain_quote.appendChild(html_p_explain_quote_txt);

	// P: the paragraph FOR random quote
	dv.appendChild(html_p_random_quote);
	html_p_random_quote.appendChild(html_p_random_quote_txt);
}

/* --------------------------------------- Date validation --------------------------------------- */

// Validate and-or correct the form input
function dateValidation() {

	// Define the fields to check
	var strInYear 	= document.getElementById('form_field_year');
	var strInMonth 	= document.getElementById('form_field_month');
	var strInDate 	= document.getElementById('form_field_date');

	// Months don't have the same number of days. Correct them
	var monthEndDates = new Array();
		monthEndDates[0] = 31;
		// leap year
		if (strInYear.value % 4 == 0) {
			monthEndDates[1] = 29;
		} else {
			monthEndDates[1] = 28;
		}
		monthEndDates[2]  = 31;
		monthEndDates[3]  = 30;
		monthEndDates[4]  = 31;
		monthEndDates[5]  = 30;
		monthEndDates[6]  = 31;
		monthEndDates[7]  = 31;
		monthEndDates[8]  = 30;
		monthEndDates[9]  = 31;
		monthEndDates[10] = 30;
		monthEndDates[11] = 31;

	var strErr = '';

	if ( ! strInYear.value.match(/[0-9]{4}/g) ) {
		strErr += 'the year is entered correctly (i.e: ' + Now.getFullYear() + ')\n';
		strInYear.style.backgroundColor = strErrColour;
	}
	if (strInYear.value > Now.getFullYear()) {
		strErr += 'the year is current or past\n';
		strInYear.style.backgroundColor = strErrColour;
	}
	if (! strInMonth.value.match(/[0-9]{1,2}/g)) {
		strErr += 'the month number is entered correctly (i.e: ' + Now.getMonth() + ')\n';
		strInMonth.style.backgroundColor = strErrColour;
	}
	if (strInMonth.value < 1 || strInMonth.value > 12) {
		strErr += 'the month number is between 1 and 12\n';
		strInMonth.style.backgroundColor = strErrColour;
	}
	if (! strInMonth.value.match(/[0-9]{1,2}/g)) {
		strErr += 'the date is entered correctly (1-31)\n';
		strInDate.style.backgroundColor = strErrColour;
	} else {
		// user inputted too many days for month, correct
		if(strInDate.value > monthEndDates[strInMonth.value-1]) {
			strInDate.value = monthEndDates[strInMonth.value-1];
		}
	}
	if (strInDate.value < 1 || strInDate.value > 31) {
		strErr += 'the date is entered correctly (i.e: ' + Now.getDate() + ')\n';
		strInDate.style.backgroundColor = strErrColour;
	}
	if (strErr.length) {
		alert('Please ensure that \n' + strErr);
	} else {
		buildResults();
	}
}


/* --------------------------------- Calculate the time span --------------------------------- */

// [1] Figure out the elapsed time
function calcTimeSpan(varNowDate, varStartDate) {
	var dtNowDate;
	var dtStart;
	var dtAnniversary;
	var intSpan;
	var intYears;
	var intMonths;
	var intWeeks;
	var intDays;
	var intHours;
	var intMinutes;
	var intSeconds;
	var strHowLong;
	var errTime;
	
	// vars to simplify reading
	var intMsPerSec  = 1000;
	var intMsPerMin  = 60000;
	var intMsPerHr   = 3600000;
	var intMsPerDay  = 86400000;
	var intMsPerWeek = 604800000;

	// Get "now" date
	dtNowDate = new Date(varNowDate);

	// Get Start date
	dtStart = new Date(varStartDate);

	// [2] If  dtStart date is before  else  error message
	if ( dtNowDate >= dtStart ) {


		/* Figure our how many days, hours, mins and seconds have passed since the start */
	
		// Get the time (hours minutes and seconds) difference from Now DATE and start DATE (not day of year; the day number of the month i.e the 21st)
		intSpan = ( dtNowDate.getUTCHours() * intMsPerHr + dtNowDate.getUTCMinutes() * intMsPerMin + dtNowDate.getUTCSeconds() * intMsPerSec ) - ( dtStart.getUTCHours() * intMsPerHr + dtStart.getUTCMinutes() * intMsPerMin + dtStart.getUTCSeconds() * intMsPerSec );

		// [3] Anniversary DATE: if now date number equal to or greater than start date number, or they are the same and there is no time difference...
		if ( dtNowDate.getUTCDate() > dtStart.getUTCDate() || ( dtNowDate.getUTCDate() == dtStart.getUTCDate() && intSpan >= 0 ) ) {

			// Most recent day (date) anniversary is in THIS month (This year, month, START date number & time is the aniversary date
			dtAnniversary = new Date( Date.UTC( dtNowDate.getUTCFullYear(), dtNowDate.getUTCMonth(), dtStart.getUTCDate(), dtStart.getUTCHours(), dtStart.getUTCMinutes(), dtStart.getUTCSeconds() ) );


		// [3] if the now date is LESS than the start date, the aniversary was before this month 
		} else {
			
			// Most recent day (date) anniversary is in month BEFORE Now month
			dtAnniversary = new Date( Date.UTC( dtNowDate.getUTCFullYear(), dtNowDate.getUTCMonth() - 1, dtStart.getUTCDate(), dtStart.getUTCHours(), dtStart.getUTCMinutes(), dtStart.getUTCSeconds() ) );

			// Get last month (this month minus 1)
			intMonths = dtNowDate.getUTCMonth() - 1;
			
			// January is 0, if it's minus 1, we want december minus 1
			if ( intMonths == -1 ) {
					  intMonths = 11;
			}

			// While month is not what it is supposed to be (it will be higher), keep moving back one day
			while ( dtAnniversary.getUTCMonth() != intMonths ) {
				dtAnniversary.setUTCDate( dtAnniversary.getUTCDate() - 1 ); // move back one day
			}

		// [3] end if
		}


		/* Figure our how many years and months have passed since the start */

		// If anniversary month is ON OR AFTER Start month
		 if ( dtAnniversary.getUTCMonth() >= dtStart.getUTCMonth() ) {

			// months elapsed is anniversary month - Start month
			intMonths = dtAnniversary.getUTCMonth() - dtStart.getUTCMonth();

			// years elapsed is anniversary year - Start year
			intYears = dtAnniversary.getUTCFullYear() - dtStart.getUTCFullYear();

			 // if Start month is AFTER anniversary month
		} else {

			// months elapsed is months left in Start year + anniversary month
			intMonths = (11 - dtStart.getUTCMonth()) + dtAnniversary.getUTCMonth() + 1;

			// years elapsed is year before anniversary year - Start year
			intYears = (dtAnniversary.getUTCFullYear() - 1) - dtStart.getUTCFullYear();
		}


		// to calculate weeks, days, hours, minutes and seconds
		// we can take the difference from anniversary date and now date

		// get time span between two dates in milliseconds
		intSpan = dtNowDate - dtAnniversary;

		// get number of weeks
		intWeeks = Math.floor(intSpan / intMsPerWeek);

		 // if there are 4 weeks, we add 1 month, and later remove the display of weeks
		 if (intWeeks == 4) {
		 	intMonths = intMonths + 1;
		 }

		//  Subtract chunks of time from time span
		intSpan = intSpan - (intWeeks * intMsPerWeek); // subtract weeks
		intDays = Math.floor(intSpan / intMsPerDay);	// get days
		intSpan = intSpan - (intDays * intMsPerDay); 	// subtract days
		intHours = Math.floor(intSpan / intMsPerHr); 	// get hours
		intSpan = intSpan - (intHours * intMsPerHr); 	// subtract hours
		intMinutes = Math.floor(intSpan / intMsPerMin); // get minutes
		intSpan = intSpan - (intMinutes * intMsPerMin); // subtract minutes
		intSeconds = Math.floor(intSpan / intMsPerSec); // get seconds

		// Create output string
		if ( intYears > 0 ) {
			strHowLong = intYears.toString() + ' Year';
			if (intYears > 1) { strHowLong = strHowLong + 's';}
		} else {
			strHowLong = '';
		}

		if ( intMonths > 0 ) {
			strHowLong = strHowLong + ' ' + intMonths.toString() + ' Month';
			if (intMonths > 1) {strHowLong = strHowLong + 's';}
		}

		// if there are weeks, but less than 4 weeks (a month that we've previously incremented)
		if ( intWeeks > 0 && intWeeks < 4) {
			strHowLong = strHowLong + ' ' + intWeeks.toString() + ' Week';
			if (intWeeks > 1) {strHowLong = strHowLong + 's';}
		}

		if ( intDays > 0 ) {
			strHowLong = strHowLong + ' ' + intDays.toString() + ' Day';
			if (intDays > 1) {strHowLong = strHowLong + 's';}
		}

		if ( intHours > 0 ) {
			strHowLong = strHowLong + ' ' + intHours.toString() + ' Hour';
			if (intHours > 1) {strHowLong = strHowLong + 's';}
		}

		if ( intMinutes > 0 ) {
			strHowLong = strHowLong + ' ' + intMinutes.toString() + ' Minute';
			if (intMinutes > 1) {strHowLong = strHowLong + 's';}
		}

		if ( intSeconds > 0 ) {
			strHowLong = strHowLong + ' ' + intSeconds.toString() + ' Second';
			if (intSeconds > 1) {strHowLong = strHowLong + 's';}
		}
		if (intYears == 0 && intMonths == 0 && intDays == 0 ) {
			errTime = 1;
			strHowLong = 'The only requirement for membership is an honest desire to stop drinking, (using drugs or acting out in an obsessive-complusive pattern of addiction).';
		}

	// [2] Now date is NOT on or after Start date
	} else {
		errTime = 1;
		strHowLong = 'Input date must be before today';
	}

	// return string representation
	if (errTime == 1) {
		return strHowLong;
	} else {
		var strHowLong = time_msg + ' ' + strHowLong;
		return strHowLong;
	}

// [1] End function
}

/* --------------------------------------- Build results --------------------------------------- */

// Create the time span output display
function buildResults() {

	// Date.UTC needs INTs...
	strInYear 	= parseInt(document.getElementById('form_field_year').value);
	strInMonth 	= parseInt(document.getElementById('form_field_month').value)-1;
	strInDate 	= parseInt(document.getElementById('form_field_date').value);

	// Build the display string
	time_span = calcTimeSpan(Date.UTC(Now.getFullYear(),Now.getMonth(),Now.getDate(),0,0,0),Date.UTC(strInYear,strInMonth,strInDate,0,0,0));

	// Identify text nodes and set their values
	p = document.getElementById('html_p_time_span');
	p_txt = p.firstChild;
	q = document.getElementById('html_p_random_quote');
	q_txt = q.firstChild;

	// Clear any previous messages and re-insert into the text node
	p_txt.nodeValue = '';
	p_txt.nodeValue = time_span;
	q_txt.nodeValue = '';
	q_txt.nodeValue = randomQuote();
}



/* --------------------------------------- Make it go --------------------------------------- */
// We are smart; we can make it go
	buildHTMLStructure();

// End of script
