/**
 * Get the BWNS RSS feed
 */
function getBWNS() {
    getRSS("feed", "BWNS News", "http://webservices.bahai.org/rss/bahainews/rssfeed.xml");
}

/**
 * This calls the server process which imports an RSS feed. The server
 * returns the XML from the feed, which is then passed to processRequest().
 */
function getRSS(paneID, title, url) {
    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?feedURL=" + url,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processRSSRequest(response, paneID, title);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while retrieving the news feed.");
        }
    });
}

/**
 * This can be used to process any RSS feed that contains a single channel.
 * If multiple channels are present, only the first will be picked up, but
 * I suspect this is not normally the case anyway.
 */
function processRSSRequest(data, paneID, paneTitle) {
    var html = "";
    var root = data.getElementsByTagName('channel')[0];
    for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
        var node = root.childNodes.item(iNode);
        if (node.nodeName == 'item') {
            var title = getChildNodeText(node, 'title');
            var link = getChildNodeText(node, 'link');
            var date = getChildNodeText(node, 'pubDate');
            var description = getChildNodeText(node, 'description');
            // If there is a double <br />, take it as the end of the first
            // paragraph and cut off the rest of the text to avoid having
            // stuff that is way long.
            var paraEnd = description.indexOf('<br /><br />');
            if (paraEnd > 0) {
                description = description.substr(0, paraEnd);
            }
            // Then remove any <p> and </p> tags embedded in the text,
            // as they mess up our formatting.
            description = description.replace(/<p>/g, '');
            description = description.replace(/<\/p>/g, '');
            html = html + '<p class="feedHeadline">' +
                   '<a href="' + link + '">' + title + '</a></p>' + 
                   '<p class="feedDate">' + date + '</p>' +
                   '<p class="feedBody">' + description + '</p>';
        }
    }
    var newsElement = dojo.byId(paneID);
    var newsTitle = newsElement.childNodes[0].childNodes[3];
    var newsBody = newsElement.childNodes[1].childNodes[0];
    newsTitle.innerHTML = paneTitle;
    newsBody.innerHTML = html;

		// Make the indicated pane the active pane
		var accordion = dijit.byId('feedaccordion');
		newsElement = dijit.byId(paneID);
		accordion.selectChild(newsElement);
}

/**
 * This calls the server process which casts a vote for an article or book
 * review. The server returns XML indicating success or failure.
 */
function castVote(itemID, itemType) {
    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?" + itemType + "vote=" + itemID,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processVoteRequest(response, itemType + itemID);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while casting a vote.");
        }
    });
}

/**
 * Process a response from a vote request.
 */
function processVoteRequest(data, elementID) {
    var root = data.getElementsByTagName('vote')[0];
    var node = root.childNodes.item(0);
    var html = '';

		if (node.nodeName == "votecount") {
		    var voteCount = node.firstChild.nodeValue;
    		var voteText = "";
				if (voteCount == 1) {
				    voteText = voteCount + " vote";
				} else {
				    voteText = voteCount + " votes";
				}
        if (elementID.substr(0,1) == "a") {
		        html = voteText + " | You voted for this article";
			  } else {
		        html = voteText + " | You voted for this book review";
        }
        var voteElement = dojo.byId(elementID);
        voteElement.innerHTML = html;
		} else if (node.nodeName == "error") {
        alert(node.firstChild.nodeValue);
		} else {
        alert("An error occurred while processing a vote request.");
		} 
}

/**
 * This calls the server process which updates a member profile based on 
 * data in profileForm fields. The server returns XML indicating success or failure.
 */
function updateProfile(memberID, adminFlag) {

    // Get data from the form
		var obj;
		var oldpw = '';
		var newpw = '';
		var newpw2 = '';
		var email = '';
		var pwprompt = '';
		var pwanswer = '';
		var newsletter = '';
		var verified = '';
		var trash = '';

		obj = dojo.byId('oldpw');
		if (obj != null) {
        oldpw = obj.value;
    }		    
		obj = dojo.byId('newpw');
		if (obj != null) {
       newpw = obj.value;
    }		    
		obj = dojo.byId('newpw2');
		if (obj != null) {
        newpw2 = obj.value;
    }		    
		obj = dojo.byId('email');
		if (obj != null) {
        email = obj.value;
    }		    
		obj = dojo.byId('prompt');
		if (obj != null) {
        pwprompt = obj.value;
    }		    
		obj = dojo.byId('answer');
		if (obj != null) {
        pwanswer = obj.value;
    }		    
		obj = dojo.byId('newsletter');
		if (obj != null) {
        if (obj.checked) {				
				    newsletter = obj.value;
				}
    }		    
		obj = dojo.byId('verified');
		if (obj != null) {
        if (obj.checked) {				
				    verified = obj.value;
				}
    }		    
		obj = dojo.byId('trash');
		if (obj != null) {
        if (obj.checked) {				
				    trash = obj.value;
				}
    }		    

    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?updatemember=" + memberID +
				                                  "&admin=" + adminFlag + 
				                                  "&oldpw=" + oldpw + 
																					"&newpw=" + newpw + 
																					"&newpw2=" + newpw2 + 
																					"&email=" + email + 
																					"&prompt=" + pwprompt + 
																					"&answer=" + pwanswer +
																					"&newsletter=" + newsletter +
																					"&verified=" + verified +
																					"&trash=" + trash,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processMPUpdateRequest(response, adminFlag);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while updating your member profile.");
        }
    });
}

/**
 * Process a response from a profile update request.
 */
function processMPUpdateRequest(data, adminFlag) {
    var root = data.getElementsByTagName('update')[0];
    var msgNode = root.childNodes.item(0);
		var profileNode = root.childNodes.item(1);
    var messageElement = dojo.byId('profileMessage');

		if ((msgNode.nodeName == "success") || (msgNode.nodeName == "error")) {
		    // Display message and clear password fields
        messageElement.innerHTML = msgNode.firstChild.nodeValue;				
				dojo.byId('oldpw').value = '';
				dojo.byId('newpw').value = '';
				dojo.byId('newpw2').value = '';
        if ((msgNode.nodeName == "error") && (profileNode != null)) {
				    // If we had an error and profile values were returned, 
						// reset the form values to the returned values
						dojo.byId('email').value = profileNode.childNodes.item(0).firstChild.nodeValue;
						dojo.byId('prompt').value = profileNode.childNodes.item(1).firstChild.nodeValue;
						dojo.byId('answer').value = profileNode.childNodes.item(2).firstChild.nodeValue;
						if (profileNode.childNodes.item(3).firstChild.nodeValue == 'Y') {
						    dojo.byId('newsletter').checked = true;
						} else {
						    dojo.byId('newsletter').checked = false;
						}
						if (adminFlag == 'Y') {
						    // Additional fields for back-end processing
    						if (profileNode.childNodes.item(3).firstChild.nodeValue == 'Y') {
    						    dojo.byId('verified').checked = true;
    						} else {
    						    dojo.byId('verified').checked = false;
    						}
    						if (profileNode.childNodes.item(3).firstChild.nodeValue == 'Y') {
    						    dojo.byId('trash').checked = true;
    						} else {
    						    dojo.byId('trash').checked = false;
    						}
						}
				}
		} else {
        alert("An error occurred while processing a member profile update request.");
		} 
}

/**
 * This calls the server process which updates an admin user profile based on 
 * data in profileForm fields. The server returns XML indicating success or failure.
 */
function updateAdminProfile(userID) {

    // Get data from the form
		var obj;
		var oldpw = '';
		var newpw = '';
		var newpw2 = '';
		var email = '';
		var pwprompt = '';
		var pwanswer = '';

		obj = dojo.byId('oldpw');
		if (obj != null) {
        oldpw = obj.value;
    }		    
		obj = dojo.byId('newpw');
		if (obj != null) {
       newpw = obj.value;
    }		    
		obj = dojo.byId('newpw2');
		if (obj != null) {
        newpw2 = obj.value;
    }		    
		obj = dojo.byId('email');
		if (obj != null) {
        email = obj.value;
    }		    
		obj = dojo.byId('prompt');
		if (obj != null) {
        pwprompt = obj.value;
    }		    
		obj = dojo.byId('answer');
		if (obj != null) {
        pwanswer = obj.value;
    }		    

    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?updateuser=" + userID +
				                                  "&oldpw=" + oldpw + 
																					"&newpw=" + newpw + 
																					"&newpw2=" + newpw2 + 
																					"&email=" + email + 
																					"&prompt=" + pwprompt + 
																					"&answer=" + pwanswer,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processAPUpdateRequest(response);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while updating your admin user profile.");
        }
    });
}

/**
 * Process a response from a profile update request.
 */
function processAPUpdateRequest(data) {
    var root = data.getElementsByTagName('update')[0];
    var msgNode = root.childNodes.item(0);
		var profileNode = root.childNodes.item(1);
    var messageElement = dojo.byId('profileMessage');

		if ((msgNode.nodeName == "success") || (msgNode.nodeName == "error")) {
		    // Display message and clear password fields
        messageElement.innerHTML = msgNode.firstChild.nodeValue;				
				dojo.byId('oldpw').value = '';
				dojo.byId('newpw').value = '';
				dojo.byId('newpw2').value = '';
        if ((msgNode.nodeName == "error") && (profileNode != null)) {
				    // If we had an error and profile values were returned, 
						// reset the form values to the returned values
						dojo.byId('email').value = profileNode.childNodes.item(0).firstChild.nodeValue;
						dojo.byId('prompt').value = profileNode.childNodes.item(1).firstChild.nodeValue;
						dojo.byId('answer').value = profileNode.childNodes.item(2).firstChild.nodeValue;
				}
		} else {
        alert("An error occurred while processing an admin user profile update request.");
		} 
}

/**
 * This calls the server process which updates admin flags for an admin user based on 
 * data in profileForm fields. The server returns XML indicating success or failure.
 */
function updateAdminFlags(userID) {

    // Get data from the form
		var obj;
		var articleeditor = '';
		var newseditor = '';
		var linkeditor = '';
		var resourceeditor = '';
		var administrator = '';

		obj = dojo.byId('articleeditor');
		if (obj != null) {
        if (obj.checked) {				
				    articleeditor = obj.value;
				}
    }		    
		obj = dojo.byId('newseditor');
		if (obj != null) {
        if (obj.checked) {				
				    newseditor = obj.value;
				}
    }		    
		obj = dojo.byId('linkeditor');
		if (obj != null) {
        if (obj.checked) {				
				    linkeditor = obj.value;
				}
    }		    
		obj = dojo.byId('resourceeditor');
		if (obj != null) {
        if (obj.checked) {				
				    resourceeditor = obj.value;
				}
    }		    
		obj = dojo.byId('administrator');
		if (obj != null) {
        if (obj.checked) {				
				    administrator = obj.value;
				}
    }		    

    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?updateflags=" + userID +
				                                  "&articleeditor=" + articleeditor + 
																					"&newseditor=" + newseditor + 
																					"&linkeditor=" + linkeditor + 
																					"&resourceeditor=" + resourceeditor + 
																					"&administrator=" + administrator,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processAFUpdateRequest(response);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while updating " + userID + "'s admin settings.");
        }
    });
}

/**
 * Process a response from an admin user flags update request.
 */
function processAFUpdateRequest(data) {
    var root = data.getElementsByTagName('update')[0];
    var msgNode = root.childNodes.item(0);
		var profileNode = root.childNodes.item(1);
    var messageElement = dojo.byId('profileMessage');

		if ((msgNode.nodeName == "success") || (msgNode.nodeName == "error")) {
		    // Display message
        messageElement.innerHTML = msgNode.firstChild.nodeValue;				
		} else {
        alert("An error occurred while processing an admin user flags update request.");
		} 
}

/**
 * This calls the server process which updates an author profile based on 
 * data in profileForm fields. The server returns XML indicating success or failure.
 */
function updateAuthorProfile(userID) {

    // Get data from the form
    var obj;
    var name = '';
    var email = '';
    var photo = '';
    var staff = '';
    var bio = '';

    obj = dojo.byId('name');
    if (obj != null) {
        name = obj.value;
    }
    obj = dojo.byId('email');
    if (obj != null) {
        email = obj.value;
    }
    obj = dojo.byId('photo');
    if (obj != null) {
        photo = obj.value;
    }
    obj = dojo.byId('staff');
    if (obj != null) {
        if (obj.checked) {
            staff = obj.value;
        }
    }

    /* Note: When using AJAX, the editor content is NOT copied to the
     *       hidden field first. Here we just pull it out of the editor.
     */
    bio = dijit.byId('editor').getValue(false);
    bio = bio.replace(/&quot;/g, '"');  /* Translate double quotes */
    bio = bio.replace(/;/g, '%3B');      /* Escape semicolons - google "URL Escape characters for full list, which needs to be implemented later on */

    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?updateauthor=" + userID +
				                                  "&name=" + name + 
												  "&email=" + email +
												  "&photo=" + photo +
												  "&staff=" + staff +
												  "&bio=" + bio,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processAuUpdateRequest(response);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while updating an author profile.");
        }
    });
}

/**
 * Process a response from an author profile update request.
 */
function processAuUpdateRequest(data) {
    var root = data.getElementsByTagName('update')[0];
    var msgNode = root.childNodes.item(0);
		var profileNode = root.childNodes.item(1);
    var messageElement = dojo.byId('profileMessage');

		if ((msgNode.nodeName == "success") || (msgNode.nodeName == "error")) {
		    // Display message 
            messageElement.innerHTML = msgNode.firstChild.nodeValue;
            if ((msgNode.nodeName == "error") && (profileNode != null)) {
				    // If we had an error and profile values were returned, 
					// reset the form values to the returned values
					dojo.byId('name').value = profileNode.childNodes.item(0).firstChild.nodeValue;
					dojo.byId('email').value = profileNode.childNodes.item(1).firstChild.nodeValue;
					dojo.byId('photo').value = profileNode.childNodes.item(2).firstChild.nodeValue;
					dojo.byId('staff').value = profileNode.childNodes.item(2).firstChild.nodeValue;
					dojo.byId('fulltext').value = profileNode.childNodes.item(2).firstChild.nodeValue;
			}
		} else {
            alert("An error occurred while processing an author profile update request.");
		} 
}

/**
 * This calls the server process which adds an RSS feed for a user based on 
 * data in addFeedForm fields. The server returns XML indicating success or failure.
 */
function addFeed(memberID) {
    // Get data from the form
		var obj;
		var feedName = '';
		var feedURL = '';

		obj = dojo.byId('feedname');
		if (obj != null) {
        feedName = obj.value;
    }		    
		obj = dojo.byId('feedurl');
		if (obj != null) {
       feedURL = obj.value;
    }		    

    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?memberid=" + memberID +
				                                  "&feedname=" + feedName + 
																					"&feedurl=" + feedURL,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processAddFeedRequest(response, memberID, feedName, feedURL);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while adding an RSS feed.");
        }
    });
}

/**
 * Process a response from an add RSS feed request.
 */
function processAddFeedRequest(data, memberID, feedName, feedURL) {
    var root = data.getElementsByTagName('addfeed')[0];
    var msgNode = root.childNodes.item(0);
    var messageElement = dojo.byId('feedMessage');

		if ((msgNode.nodeName == "success")) {
        // Display new header message and feed list				
    		var feedListNode = root.childNodes.item(1);
				dojo.byId('feedHeader').innerHTML = feedListNode.firstChild.firstChild.nodeValue;
				dojo.byId('feedList').innerHTML = feedListNode.childNodes.item(1).firstChild.nodeValue;
		    // Display results message and clear form fields
        messageElement.innerHTML = msgNode.firstChild.nodeValue;
				dojo.byId('feedname').value = '';
				dojo.byId('feedurl').value = '';
		} else {
        alert("An error occurred while processing an RSS feed add request.");
		} 
}

/**
 * This calls the server process which deletes an RSS feed for a member based. 
 * The server returns XML indicating success or failure.
 */
function deleteFeed(memberID, feedID) {
    dojo.xhrGet( {
        url: "/cgi-bin/ajaxhandler.pl?memberid=" + memberID +
				                                  "&delfeed=" + feedID,
        handleAs: "xml",
        timeout: 8000,
        load: function(response, ioArgs) {
            processDeleteFeedRequest(response);
        },
        error: function(response, ioArgs) {
            alert("An error occurred while deleting an RSS feed.");
        }
    });
}

/**
 * Process a response from a delete RSS feed request.
 */
function processDeleteFeedRequest(data) {
    var root = data.getElementsByTagName('delfeed')[0];
    var msgNode = root.childNodes.item(0);
    var messageElement = dojo.byId('feedMessage');

    if ((msgNode.nodeName == "success")) {
        // Display new header message and feed list
        var feedListNode = root.childNodes.item(1);
        dojo.byId('feedHeader').innerHTML = feedListNode.firstChild.firstChild.nodeValue;
        dojo.byId('feedList').innerHTML = feedListNode.childNodes.item(1).firstChild.nodeValue;
        // Display results message
        messageElement.innerHTML = msgNode.firstChild.nodeValue;
    } else {
        alert("An error occurred while processing an RSS feed add request.");
    }
}

/**
 * This calls the server process which validates a member ID on the signup form.
 * The server returns XML indicating a valid or invalid ID.
 */
function checkID() {
    var id = dojo.byId('id').value;
    if (id.length > 0) {
        dojo.xhrGet( {
            url: "/cgi-bin/ajaxhandler.pl?validateid=" + id,
            handleAs: "xml",
            timeout: 8000,
            load: function(response, ioArgs) {
                processCheckIDRequest(response);
            },
            error: function(response, ioArgs) {
                alert("An error occurred while validating a member ID.");
            }
        });
    } else {
        dojo.byId('validationMessage').innerHTML = '';
    }
}

/**
 * Process a response from a member ID validation request.
 */
function processCheckIDRequest(data) {
    var root = data.getElementsByTagName('validate')[0];
    var msgNode = root.childNodes.item(0);
    var messageElement = dojo.byId('validationMessage');

		if ((msgNode.nodeName == "valid") || (msgNode.nodeName == "invalid")) {
		    // Display message
            messageElement.innerHTML = '&nbsp;&nbsp;' + msgNode.firstChild.nodeValue;
            // Set the style to be used
            if (msgNode.nodeName == "valid") {
				messageElement.className = 'okMessage';
                dojo.byId('send').disabled = false;
            } else {
				messageElement.className = 'alertMessage';
                dojo.byId('send').disabled = true;
			}
		} else {
            alert("An error occurred while processing a member ID validation request.");
		}
}

/**
 * Return the text inside a specified child node.
 */
function getChildNodeText(node, name) {
    return node.getElementsByTagName(name)[0].childNodes[0].nodeValue;
}

/**
 * Clear the specified message area 
 */
function clearMessage(messageID) {
    var messageElement = dojo.byId(messageID);
    messageElement.innerHTML = '';
}

/**
 * Copy content from editor to a hidden form parameter's value
 */
function copyEditorContent(evt) {
    content = dijit.byId('editor').getValue(false);
    if(!content) {
        alert("Please enter full text content.");
        evt.preventDefault();
    }
    dojo.byId('fulltext').value = content;
}

/**
 * Connect a form submit event to copyEditorContent
 */
function connectEditor() {
    dojo.connect(dojo.byId('dataform'), 'onsubmit', copyEditorContent)
}

/**
 * Show a menu
 */
function show(id) {
    var d = document.getElementById(id);
        for (var i = 1; i<=10; i++) {
            if (document.getElementById('smenu'+i)) {
                document.getElementById('smenu'+i).style.display='none';
            }
        }
    if (d) {d.style.display='block';}
}

/**
 * Toggles the visblity state of an element
 */
function toggleVisible(id) {
    var e = dojo.byId(id);
		
		if (e.style.display == 'none') {
		    e.style.display = '';
		} else {
		    e.style.display = 'none';
		}
}

/**
 * Display the current date and any applicable holiday information
 */
function displayDate() {
     calendar = new Date();
     day = calendar.getDay();
     month = calendar.getMonth();
     date = calendar.getDate();
     year = calendar.getYear();
     if (year < 1000)
       year+=1900
       cent = parseInt(year/100);
     g = year % 19;
     k = parseInt((cent - 17)/25);
     i = (cent - parseInt(cent/4) - parseInt((cent - k)/3) + 19*g + 15) % 30;
     i = i - parseInt(i/28)*(1 - parseInt(i/28)*parseInt(29/(i+1))*parseInt((21-g)/11));
     j = (year + parseInt(year/4) + i + 2 - cent + parseInt(cent/4)) % 7;
     l = i - j;
     emonth = 3 + parseInt((l + 40)/44);
     edate = l + 28 - 31*parseInt((emonth/4));
     emonth--;
     var dayname = new Array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
     var monthname = new Array ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" );
     var dateText = "";
     dateText = dateText + dayname[day] + ", ";
     dateText = dateText + monthname[month] + " ";
     dateText = dateText + date + ", ";
     dateText = dateText + year;
     // Easter
     if ((month == emonth) && (date == edate)) dateText = dateText + " - Easter Sunday (Western)   ";
     // January
     if ((month == 0) && (date == 1)) dateText = dateText + " - New Year's Day";
     if ((month == 0) && (day == 1) && (date > 14) && (date< 22)) dateText = dateText + " - Martin Luther King's Birthday";
     // February
     if ((month == 1) && (date== 12)) dateText = dateText + " - Lincoln's Birthday";
     // March
     if ((month == 2) && (date == 21)) dateText = dateText + " - Naw-Rúz";
     // April
     if ((month == 3) && (date == 21)) dateText = dateText + " - First Day of Ridván";
     if ((month == 3) && (date == 22)) dateText = dateText + " - Earth Day";
     if ((month == 3) && (date == 29)) dateText = dateText + " - Ninth Day of Ridván";
     // May
     if ((month == 4) && (date == 2)) dateText = dateText + " - Twelfth Day of Ridván";
     if ((month == 4) && (date == 23)) dateText = dateText + " - Declaration of the Báb";
     if ((month == 4) && (day == 1) && (date > 24)) dateText = dateText + " - Memorial Day";
     if ((month == 4) && (date == 29)) dateText = dateText + " - Ascension of Bahá'u'lláh";
     // June
     if ((month == 5) && (date == 21)) dateText = dateText + " - Summer Solstice";
     // July
     if ((month == 6) && (date == 9)) dateText = dateText + " - Martyrdom of the Báb";
     // August
     // September
     // October
     if ((month == 9) && (date == 20)) dateText = dateText + " - Birth of the Báb";
     if ((month == 9) && (date == 24)) dateText = dateText + " - United Nations Day";
     if ((month == 9) && (date == 31)) dateText = dateText + " - Halloween";
     // November
     if ((month == 10) && (date == 1)) dateText = dateText + " - All Saints Day";
     if ((month == 10) && (date == 2)) dateText = dateText + " - All Souls Day";
     if ((month == 10) && (date == 12)) dateText = dateText + " - Birth of Bahá'u'lláh";
     if ((month == 10) && (date == 26)) dateText = dateText + " - Day of the Covenant";
     if ((month == 10) && (date == 28)) dateText = dateText + " - Ascension of 'Abdu'l-Bahá";
     // December
     if ((month == 11) && (date == 10)) dateText = dateText + " - Human Rights Day";
     if ((month == 11) && (date == 21)) dateText = dateText + " - Winter Solstice";
     if ((month == 11) && (date == 25)) dateText = dateText + " - Christmas";
     // Write the result to the page
     var dateElement = dojo.byId("dateLine");
     dateElement.innerHTML = dateText;
}

/**
 * Create an email link for an author
 */
function EmailLink(AuthorName) {
     var Authors = ['me', 'Dale', 'Kathleen', 'Duane', 'Simon', 'Amy', 'Julie'];
		 var Emails = ["mailto:dlehman",
                   "mailto:dlehman",
                   "mailto:klehman",
                   "mailto:ddawson",
                   "mailto:scameron",
                   "mailto:aharmony",
                   "mailto:jhammond"
					   ];
     var i;
		 
     for (i=0;i<Authors.length;i++) {
          if (Authors[i]==AuthorName) {
               // Build numbered text for current row
               document.write("<a href='" + Emails[i] + "@planetbahai.org'>" + AuthorName + "</a>");
          }
     }
}

/**
 * Create an online Baha'i Calendar
 */
function DisplayCalendar(TableBackColor, Title1BackColor, Title2BackColor, Day1Color, HolyDayColor, AyyamiHaTitleColor,
                         StartDayOfWeek, LeapYear, Language) {
     var GMonthNames;
     var BMonthNames;
     var GMonthLengths = ['31','28','31','30','31','30','31','31','30','31','30','31'];
     var CurrentGMonth = 2; //Always starts with March 
     var CurrentGDay = 21;  //Always starts on the 21st
     var CurrentBMonth;
     var CurrentBDay;
     var MaxBDay;
     var DayOfWeek = StartDayOfWeek; //Day of week for March 21st passed in as parameter
     var BuildDayOfWeek;
     var HolyDayHTML;

     if (Language == 'Spanish') {
          GMonthNames = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
          BMonthNames = ["Bah&aacute; (Esplendor)","Jal&aacute;l (Gloria)","Jam&aacute;l (Belleza)",
                         "'Azamat (Grandeza)","N&uacute;r (Luz)","Rahmat (Misericordia)","Kalim&aacute;t (Palabras)",
                         "Kam&aacute;l (Perfecci&oacute;n)","Asm&aacute;' (Nombres)","'Izzat (Fuerza)","Ma<U>sh</U>&iacute;yyat (Voluntad)",
                         "'Ilm (Conocimiento)","Qudrat (Poder)","Qawl (Discurso)","Mas&aacute;'il (Preguntas)","<U>Sh</U>araf (Honor)",
                         "Sult&aacute;n (Soberan&iacute;a)","Mulk (Dominio)","Ayy&aacute;m-i-H&aacute; (Dias Intercalares)",
                         "'Al&aacute; (Sublimidad) - El Ayuno de 19 D&iacute;as"];
     } else {
          // English is default language
          GMonthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
          BMonthNames = ["Bah&aacute; (Splendour)","Jal&aacute;l (Glory)","Jam&aacute;l (Beauty)",
                         "'Azamat (Grandeur)","N&uacute;r (Light)","Rahmat (Mercy)","Kalim&aacute;t (Words)",
                         "Kam&aacute;l (Perfection)","Asm&aacute;' (Names)","'Izzat (Might)","Ma<U>sh</U>&iacute;yyat (Will)",
                         "'Ilm (Knowledge)","Qudrat (Power)","Qawl (Speech)","Mas&aacute;'il (Questions)","<U>Sh</U>araf (Honor)",
                         "Sult&aacute;n (Sovereignty)","Mulk (Dominion)","Ayy&aacute;m-i-H&aacute; (Intercalary Days)",
                         "'Al&aacute; (Loftiness) - The 19-Day Fast"];
     }
     if (LeapYear == 'Y') {
          // Change February month length
          GMonthLengths[1] = '29';
     }

     for (CurrentBMonth=0; CurrentBMonth<=19; CurrentBMonth++) {
          // Main loop - builds each Baha'i month in turn
          document.write("<table border cols='7' bgcolor='" + TableBackColor + "' width=100%>");
          if (CurrentBMonth == 18) {
               document.write("<tr bgcolor='" + AyyamiHaTitleColor + "'><td colspan='7'>");
          } else {
               document.write("<tr bgcolor='" + Title1BackColor + "'><td colspan='7'>");
          }
          document.write("<center><font size=+1>" + BMonthNames[CurrentBMonth] + "</center>");
          document.write("</td></tr>");
          document.write("<tr bgcolor='" + Title2BackColor + "' align=center>");
          if (Language == 'Spanish') {
               document.write("<td width=14%><font size=-1>Jal&aacute;l<br>(Gloria)<br>S&aacute;bado</font></td>");
               document.write("<td width=14%><font size=-1>Jam&aacute;l<br>(Belleza)<br>Domingo</font></td>");
               document.write("<td width=14%><font size=-1>Kam&aacute;l<br>(Perfecci&oacute;n)<br>Lunes</font></td>");
               document.write("<td width=14%><font size=-1>Fid&aacute;l<br>(Gracia)<br>Martes</font></td>");
               document.write("<td width=14%><font size=-1>'Id&aacute;l<br>(Justicia)<br>Mi&eacute;rcoles</font></td>");
               document.write("<td width=14%><font size=-1>Istijl&aacute;l<br>(Majestad)<br>Jueves</font></td>");
               document.write("<td width=14%><font size=-1>Istiql&aacute;l<br>(Independencia)<br>Viernes</font></td>");
               document.write("</tr>");
          } else {
               // English is default language
               document.write("<td width=14%><font size=-1>Jal&aacute;l<br>(Glory)<br>Saturday</font></td>");
               document.write("<td width=14%><font size=-1>Jam&aacute;l<br>(Beauty)<br>Sunday</font></td>");
               document.write("<td width=14%><font size=-1>Kam&aacute;l<br>(Perfection)<br>Monday</font></td>");
               document.write("<td width=14%><font size=-1>Fid&aacute;l<br>(Grace)<br>Tuesday</font></td>");
               document.write("<td width=14%><font size=-1>'Id&aacute;l<br>(Justice)<br>Wednesday</font></td>");
               document.write("<td width=14%><font size=-1>Istijl&aacute;l<br>(Majesty)<br>Thursday</font></td>");
               document.write("<td width=14%><font size=-1>Istiql&aacute;l<br>(Independence)<br>Friday</font></td>");
               document.write("</tr>");
          }
          // Set max days in Baha'i month (required to account for Ayyam-i-Ha)
          if (CurrentBMonth == 18) {
               if (LeapYear == 'Y') {
                    MaxBDay = 5;
               } else {
                    MaxBDay = 4;
               } 
          } else {
               MaxBDay = 19;
          }
          CurrentBDay = 1;
          do {
               // Week loop - builds each week in the month in turn
              document.write("<tr valign='top'>");
              for (BuildDayOfWeek=1; BuildDayOfWeek<=7; BuildDayOfWeek++) {
                   // Day loop - builds each day cell in the week in turn
                   if ((BuildDayOfWeek < DayOfWeek) || (CurrentBDay > MaxBDay)) {
                        // This day is not used
                        document.write("<td>&nbsp;</td>");
                   } else {
                        HolyDayHTML = '';
                        if (CurrentBMonth == 0 && CurrentBDay == 1) {
                             HolyDayHTML = "<table width=100%><tr><td bgcolor='" + HolyDayColor +
                                           "'>Naw-R&uacute;z<br>&nbsp;</td></tr></table>";
                        }
                        if (Language == 'Spanish') {
                             if (CurrentBMonth == 1 && CurrentBDay == 13) {
                                  HolyDayHTML = "<br>Primer Dia de Ridv&aacute;n";
                             }
                             if (CurrentBMonth == 2 && CurrentBDay == 2) {
                                  HolyDayHTML = "<br>Noveno Dia de Ridv&aacute;n";
                             }
                             if (CurrentBMonth == 2 && CurrentBDay == 5) {
                                  HolyDayHTML = "<br>Doceavo Dia de Ridv&aacute;n";
                             }
                             if (CurrentBMonth == 3 && CurrentBDay == 7) {
                                  HolyDayHTML = "<br>Declaraci&oacute;n del B&aacute;b";
                             }
                             if (CurrentBMonth == 3 && CurrentBDay == 13) {
                                  HolyDayHTML = "<br>Ascension de Bah&aacute;'u'll&aacute;h";
                             }
                             if (CurrentBMonth == 5 && CurrentBDay == 16) {
                                  HolyDayHTML = "<br>Martirio del B&aacute;b";
                             }
                             if (CurrentBMonth == 11 && CurrentBDay == 5) {
                                  HolyDayHTML = "<br>Nacimiento del B&aacute;b";
                             }
                             if (CurrentBMonth == 12 && CurrentBDay == 9) {
                                  HolyDayHTML = "<br>Nacimiento de Bah&aacute;'u'll&aacute;h";
                             }
                             if (CurrentBMonth == 13 && CurrentBDay == 4) {
                                  HolyDayHTML = "<br>D&iacute;a del Convenio";
                             }
                             if (CurrentBMonth == 13 && CurrentBDay == 6) {
                                  HolyDayHTML = "<br>Ascensi&oacute;n de 'Abdu'l-Bah&aacute;";
                             }
                        } else {
                             // English is default language
                             if (CurrentBMonth == 1 && CurrentBDay == 13) {
                                  HolyDayHTML = "<br>1st Day of Ridv&aacute;n";
                             }
                             if (CurrentBMonth == 2 && CurrentBDay == 2) {
                                  HolyDayHTML = "<br>9th Day of Ridv&aacute;n";
                             }
                             if (CurrentBMonth == 2 && CurrentBDay == 5) {
                                  HolyDayHTML = "<br>12h Day of Ridv&aacute;n";
                             }
                             if (CurrentBMonth == 3 && CurrentBDay == 7) {
                                  HolyDayHTML = "<br>Declaration of the B&aacute;b";
                             }
                             if (CurrentBMonth == 3 && CurrentBDay == 13) {
                                  HolyDayHTML = "<br>Ascension of Bah&aacute;'u'll&aacute;h";
                             }
                             if (CurrentBMonth == 5 && CurrentBDay == 16) {
                                  HolyDayHTML = "<br>Martyrdom of the B&aacute;b";
                             }
                             if (CurrentBMonth == 11 && CurrentBDay == 5) {
                                  HolyDayHTML = "<br>Birth of the B&aacute;b";
                             }
                             if (CurrentBMonth == 12 && CurrentBDay == 9) {
                                  HolyDayHTML = "<br>Birth of Bah&aacute;'u'll&aacute;h";
                             }
                             if (CurrentBMonth == 13 && CurrentBDay == 4) {
                                  HolyDayHTML = "<br>Day of the Covenant";
                             }
                             if (CurrentBMonth == 13 && CurrentBDay == 6) {
                                  HolyDayHTML = "<br>Ascension of 'Abdu'l-Bah&aacute;";
                             }
                        }
                        if (CurrentBDay == 1) {
                             document.write("<td bgcolor='" + Day1Color + "'>");
                        } else {
                             if (HolyDayHTML != '') {
                                  document.write("<td bgcolor='" + HolyDayColor + "'>");
                             } else {                             
                                  document.write("<td>");
                             }
                        }
                        if (HolyDayHTML == '') {
                             document.write(CurrentBDay + "<br>(" + GMonthNames[CurrentGMonth] + " " + CurrentGDay +
                                                                ")<br>&nbsp;<br>&nbsp;</td>");
                        } else {
                             document.write(CurrentBDay + "<br>(" + GMonthNames[CurrentGMonth] + " " + CurrentGDay + ")" +
                                            HolyDayHTML + "</td>");
                        }
                        CurrentBDay++;
                        CurrentGDay++;
                        if (CurrentGDay > GMonthLengths[CurrentGMonth]) {
                             // Roll to first day of next month
                             CurrentGMonth++;
                             CurrentGDay = 1;
                             if (CurrentGMonth > 11) {
                                  // Roll from December to January
                                  CurrentGMonth = 0;
                             }
                        }
                        DayOfWeek++;
                        if (DayOfWeek > 7) {
                             // Roll from last day of week to first
                             DayOfWeek = 1;
                        }
                   }                   
              }
              document.write("</tr>");
          } while (CurrentBDay <= MaxBDay)
          // Separate month tables
          document.write("</table><p>&nbsp;");
     }
}

