// GET ELEMENT BY ID
function getElement(id) {
	return document.getElementById(id);
}

// ADD STARTSWITH TO STRING METHODS
String.prototype.startsWith = function(sStart) {
    return (this.substr(0,sStart.length)==sStart);
}

// ADD ENDSWITH TO STRING METHODS
String.prototype.endsWith = function(sEnd) {
    return (this.substr(this.length-sEnd.length)==sEnd);
}

// ADD TRIM TO STRING METHODS
String.prototype.trim = function() {
	return (this.replace(/^\s*|\s*$/g,""));
}

// ADD IN_ARRAY TO ARRAY METHODS
Array.prototype.in_array = function(needle) {
	if(this.length > 0) {
		var i = this.length;
		do {
			if(this[i] === needle) return true;
		} while(i--);
	}
	return false;
}

Date.prototype.ymd = function() {
	return ''+this.getFullYear()+(this.getMonth().pad()+1)+this.getDate().pad();
}

Date.prototype.hms = function() {
	return ''+this.getHours().pad()+this.getMinutes()+this.getSeconds().pad();
}

Date.prototype.hm = function() {
	return ''+this.getHours().pad()+this.getMinutes();
}

Date.prototype.getMonthAbbrev = function() {
	var month = this.getMonth()+1;
	if(month == 1) return 'Jan';
	else if(month == 2) return 'Feb';
	else if(month == 3) return 'Mar';
	else if(month == 4) return 'Apr';
	else if(month == 5) return 'May';
	else if(month == 6) return 'Jun';
	else if(month == 7) return 'Jul';
	else if(month == 8) return 'Aug';
	else if(month == 9) return 'Sep';
	else if(month == 10) return 'Oct';
	else if(month == 11) return 'Nov';
	else if(month == 12) return 'Dec';
}

Date.prototype.md = function() {
	return this.getMonthAbbrev()+' '+this.getDate();
}

Date.prototype.moveSeconds = function(seconds) {
	var time = this.getTime();
	time += seconds * 1000;
	this.setTime(time);
}
	

Number.prototype.pad = function() {
	if(this < 10) return '0'+this;
	else return this;
}


function getCheckedRadio(item) {
    if(item && item[0]) { 
		for(var i=0; i < item.length; i++) {
			if(item[i].checked) return item[i];
		}
	} else if(item && item.checked) {
		return item;
	} else {
		return false;
	}
}

// ALL-CAPS CHECKER
function capitalizeMe(str) {
        newVal = '';
    	str = str.toLowerCase();
        str = str.split(' ');
        for(c=0; c < str.length; c++) {
			newVal += str[c].substring(0,1).toUpperCase() + str[c].substring(1,str[c].length) + ' ';
        }
        return newVal;
}

// INSERT ROW INTO TABLE
function insertTableRow(table, cellCount, rowIndex) {
	if(table && cellCount > 0) {
		if(!rowIndex) rowIndex = -1;
		var row = table.insertRow(rowIndex);
		for(var i=0; i < cellCount; i++) {
			row.insertCell(-1);
		}
		return row;
	}
}


function checkCase(str) {
	var ref = 0;
	for (i = 0; i < str.length; i++) {
		if (str.charCodeAt(i) > 64 && str.charCodeAt(i) < 90) {
			ref++;
		}
	}
	if (ref * 10 / str.length > 5) {
		alert("Whoa! No yelling on the Vine please. We have lowercased your headline for you. :)");		
		str = capitalizeMe(str);
		return str;
	} else {
		return false;
	}
}

// TYPE HERE CLASS
function typeHere(thisItem, mode) {
	if(mode) thisItem.className = 'typeHereOn';
	else thisItem.className = 'typeHereOff';
	
	if(thisItem.value && (thisItem.value == 'Type Your Article Here ...' || thisItem.value == 'Type Your Headline Here ...')) {
		thisItem.value = '';
	}
	
}


// GET WINDOW HEIGHT
function getWindowHeight() {
	if(self.innerHeight) {
		return self.innerHeight;
	} else if(document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	} else if(document.body) {
		return document.body.clientHeight;
	}
}


// GET WINDOW WIDTH
function getWindowWidth() {
	if(self.innerHeight) {
		return self.innerWidth;
	} else if(document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	} else if(document.body) {
		return document.body.clientWidth;
	}
}


function togglePlural(div, count) {
	if(div) {
		if(count == 1) div.innerHTML = '';
		else div.innerHTML = 's';
	}
}


// XML-NODE FUN
function getNodeValue(parentNode, childNodeName) {
	var node = getChildNode(parentNode, childNodeName);
	return getValueOfNode(node);
}

function getChildNode(parentNode, childNodeName) {
	var nodes = parentNode.getElementsByTagName(childNodeName);
	if(nodes.length > 0) {
		return nodes[0];
	}
}

function getValueOfNode(node) {
	if(node && node.hasChildNodes()) {
		for(var i=0; i < node.childNodes.length; i++) {
			if(node.childNodes.length > i && node.childNodes[i] && node.childNodes[i].nodeValue) {
				return node.childNodes[i].nodeValue.trim();
			}
		}
	}
}


// GENERIC BROWSER/PLATFORM DETECT
function DetectIt () {

	this.detect = navigator.userAgent.toLowerCase();
	this.OS;
	this.browser;
	this.version;
	this.thestring;
	
	this.checkIt = detectIt_checkIt;
	
	if (this.checkIt('konqueror'))	{
		this.browser = "Konqueror";
		this.OS = "Linux";
	}
	
	else if (this.checkIt('safari')) this.browser = "safari";
	else if (this.checkIt('omniweb')) this.browser = "omniweb";
	else if (this.checkIt('opera')) this.browser = "opera";
	else if (this.checkIt('webtv')) this.browser = "webtv";
	else if (this.checkIt('icab')) this.browser = "icab";
	else if (this.checkIt('msie')) this.browser = "ie";
	else if (this.checkIt('firefox')) this.browser = "firefox";
	else if (!this.checkIt('compatible'))	{
		this.browser = "netscape";
		this.version = this.detect.charAt(8);
	}
	
	else this.browser = "An unknown browser";
	
	if (!this.version) this.version = this.detect.charAt(this.place + this.thestring.length);
	
	if (!this.OS)	{
		if (this.checkIt('linux')) this.OS = "linux";
		else if (this.checkIt('x11')) this.OS = "unix";
		else if (this.checkIt('mac')) this.OS = "mac"
		else if (this.checkIt('win')) this.OS = "windows"
		else this.OS = "an unknown operating system";
	}

}

function detectIt_checkIt(string)	{
	place = this.detect.indexOf(string) + 1;
	this.thestring = string;
	return place;
}

detect = new DetectIt();


// COMMENT PREVIEW

var sStart = 0;
var tStart = 0;
var currKey = 0;

function showPreview() {
		currKey++;
		var elementy = this.id;
		setTimeout("doPreview('"+elementy+"','"+currKey+"')",500);
}

function countWords(text) {
	var text = text.replace(/(<([^>]+)>)/ig,'').replace(/(\r\n|\n|\t)/ig,' ').replace(/ ( )*/ig,' ').trim();
	var wordCount = !text ? 0 : text.split(' ').length;
	return wordCount;
}


function doPreview(elementy,newKey) {
	var tDate = new Date();
	var tDiff = tDate.getTime();
	tStart = tDate.setTime(tDiff);
	if (newKey == currKey || tStart - 1000 > sStart) {
		var sDate = new Date();
		var sDiff = sDate.getTime();
		sStart = sDate.setTime(sDiff);

		getElement('textDisplay').innerHTML =
			'<p>'+getElement(elementy).value
			.replace(/<img\s*\/*>/gi,'')
			.replace(/<h1\s*\/*>/gi,'')
			.replace(/<table\s*\/*>/gi,'')
			.replace(/<span\s*\/*>/gi,'')
			.replace(/<div\s*\/*>/gi,'')								
			.replace(/(\r\n|\n)/gi,'<br />')
			.replace(/(<br \/>){2,}/gi,'<'+'/p><p>')+'<'+'/p>';
		if (urlsokay != 1) {
			getElement('textDisplay').innerHTML =
				getElement('textDisplay').innerHTML
				.replace(/<a\s+.+\/a\s*>/gi,'<span style="color: #990000">LINKS OMITTED</span>')
				.replace(/[\w\.\-:\/]+\.\w\w\w?\/[\+:=@\w\/\.&~%;$\-|,!?]*/gi,'<span style="color: #990000">LINKS OMITTED</span>')
				.replace(/[htfn]+tp[s]*:\/\/[\+:=@\w\/\.&~%;$\-|,!?]+/gi,'<span style="color: #990000">LINKS OMITTED</span>');
		}

		if(vine && vine.modules.content.comments.commentForm.showWordCount) {
			var wordCount = countWords(getElement(elementy).value);
			getElement('wordCountSpan').innerHTML = wordCount+' word'+(wordCount == 1 ? '' : 's')+' (150 words max)';
		}

	}
}

function doComment() {
	vine.commentPoke('common-290', 'starting post');
	items = getElement('commentsForm').elements;
	var wordCount = countWords(items["commentsText_"+currentCommentBox].value.trim());
	if(!items["commentsText_"+currentCommentBox].value.trim()) {
		alert('Please make sure the Comments field contains a comment before clicking Post.');
	} else if((items.displayName && !items.displayName.value) || (items.email && !items.email.value)) {
		items.displayName.focus();
		alert('Your Name and Email Address are required to post a comment.');
	} else if(vine && vine.modules.content.comments.commentForm.wordCountLimit > 0 && wordCount > vine.modules.content.comments.commentForm.wordCountLimit) {
		alert('You have exceeded the '+vine.modules.content.comments.commentForm.wordCountLimit+' word limit.');
	} else if(items.displayName || items.email) {
		var data = 'commentReg=post&email='+encodeURIComponent(trim(items.email.value))+'&displayName='+encodeURIComponent(trim(items.displayName.value));
		doAjax('/_tools/new/user', function(ajax) {
			if(ajax.responseText == 3) {
				alert('Please enter a valid email address.');
				return false;
			} else if(ajax.responseText == 2) {
				getElement('commentsForm').action = vine.toolRoot+'/user/commentLogin';
				doCommentPost();
			} else if(ajax.responseText == 1) {
				doCommentPost();
			}
		}, data);
	} else {
		vine.commentPoke('common-312', 'calling doCommentPost');
		doCommentPost();
	}
}


function doCommentPost() {
	getElement('postingCommentImage').style.display = 'inline';
	getElement('postCommentImage').style.display = 'none';
	if (getElement('postCommentAndVoteImage')) {
		getElement('postingCommentAndVoteImage').style.display = 'inline';
		getElement('postCommentAndVoteImage').style.display = 'none';
	}
	//if voting as well
	var timeout = 100;
	if (getElement('alsoVotecheck') && getElement('alsoVotecheck').value == "on")
	{
		timeout = 500;
		sendVote(document.forms.commentsForm.contentId.value);
	}
	vine.commentPoke('common-330', 'calling submitCommentForm via timeout');
	setTimeout('submitCommentForm();', timeout);
	window.onunload = resetCommentImage;
}

function resetCommentImage() {
	getElement('postingCommentImage').style.display = 'none';
	getElement('postCommentImage').style.display = 'inline';
}


function submitCommentForm() {
	if(getElement('newThreadForm') && getCheckedRadio(getElement('newThreadForm').elements.groupId)) {
		getElement('commentsForm').elements.groupId.value = getCheckedRadio(getElement('newThreadForm').elements.groupId).value;
		getElement('commentsForm').elements.threadId.value = -1;
		if(getElement('sendNotification') && getElement('sendNotification').checked) getElement('commentsForm').elements.sendNotification.value = 1;
	} else if(getElement('newThreadForm') && getCheckedRadio(getElement('newThreadForm').elements.friendListId)) {
		var friendListId = getCheckedRadio(getElement('newThreadForm').elements.friendListId).value;
		if(friendListId == -1) friendListId = -10; // lame hack for posting a private comment to all friends
		if(friendListId*1 == friendListId) { // lame hack to ensure that friendListId is an int
			getElement('commentsForm').elements.friendListId.value = friendListId;
			getElement('commentsForm').elements.threadId.value = -1;
		} else { // friendlistId is the divId of a new friend list to be created
			var item = vine.friendLists[friendListId];
			var list = '';
			for(var i=0; i < item.friends.length; i++) {
				list += item.friends[i].domainName+',';
			}
			var input = document.createElement('input');
			input.type = 'hidden';
			input.name = 'friendListMembers';
			input.value = list;
			getElement('commentsForm').appendChild(input);
			getElement('commentsForm').elements.friendListId.value = item.label; // pass the friend list name as the friendlistId
			getElement('commentsForm').elements.threadId.value = -1;
		}
		if(getElement('sendNotification') && getElement('sendNotification').checked) getElement('commentsForm').elements.sendNotification.value = 1;
	}		
	vine.commentPoke('common-368', 'submitting form');
	doAjaxCommentPost(getElement('commentsForm'));

}


function doAjaxCommentPost(form) {
	var data = getCommentPostData(form);
	commentFormId = form.id;
	doAjax('/_action/user/doComment', function(ajax) {
		if(ajax.responseText.indexOf('redirect=') == 0) {
			var redirect = ajax.responseText.replace('redirect=', '').trim();
			if(!redirect && vine.modules.content.comments.commentForm.retries < 1) {
 				vine.modules.content.comments.commentForm.retries++;
				doAjaxCommentPost(getElement(commentFormId));
			} else if(redirect.indexOf('error=') == 0) {
				var errmsg = redirect.replace('error=', '').trim();
				alert(errmsg);
				unsetCommentButtons();
			} else if(!redirect && vine.modules.content.comments.commentForm.retries >= 1) {
				alert('Apologies, but an error has occurred.\n\nYour comment could not be posted. Please try posting your comment again. If this problem persists, please contact help@newsvine.com and let us know that you received error code: "Ragamuffin".\n\nThank you.');
 				vine.modules.content.comments.commentForm.retries = 0;
				unsetCommentButtons();
				var debug = 'subj='+encodeURIComponent('Comment Bomb - Ragamuffin')+'&msg='+encodeURIComponent('Comment post failed, common.js line 407. No redirect URL was specified in the browser response. \n\nResponse='+ajax.responseText);
				doAjax('/_action/admin/debug', null, debug);
			} else {
				location.href = redirect;
			}
		} else {
			alert('Apologies, but an error has occurred.\n\nYour comment could not be posted. Please try posting your comment again. If this problem persists, please contact help@newsvine.com and let us know that you received error code: "Spiceweasel".\n\nThank you.');
			vine.modules.content.comments.commentForm.retries = 0;
			unsetCommentButtons();
			var debug = 'subj='+encodeURIComponent('Comment Bomb - Spiceweasel')+'&msg='+encodeURIComponent('Comment post failed, common.js line 414. The response from the browser was an unexpected response. \n\nResponse='+ajax.responseText);
			doAjax('/_action/admin/debug', null, debug);
		}
	}, data);
}


function unsetCommentButtons() {
	if(getElement('postingCommentImage')) getElement('postingCommentImage').style.display = 'none';
	if(getElement('postCommentImage')) getElement('postCommentImage').style.display = 'inline';
	if (getElement('postCommentAndVoteImage')) {
		getElement('postingCommentAndVoteImage').style.display = 'none';
		getElement('postCommentAndVoteImage').style.display = 'inline';
	}
	vine.commentPokeNum	= 1;
}


function getCommentPostData(form) {
	var data = '';
	var items = form.elements;
	
	if(items.contentId) data += 'contentId='+items.contentId.value+'&';
	if(items.groupId) data += 'groupId='+items.groupId.value+'&';
	if(items.friendListId) data += 'friendListId='+encodeURIComponent(items.friendListId.value)+'&';
	if(items.threadId) data += 'threadId='+items.threadId.value+'&';
	if(items.redirect) data += 'redirect='+encodeURIComponent(items.redirect.value)+'&';
	if(items.parentId) data += 'parentId='+items.parentId.value+'&';
	if(items.sendNotification) data += 'sendNotification='+items.sendNotification.value+'&';
	if(items.replyToId) data += 'replyToId='+items.replyToId.value+'&';
	if(items.alsoVote) data += 'alsoVote='+items.alsoVote.value+'&';

	for(var i=0; i < items.length; i++) {
		if(items[i].name.startsWith('commentsText')) {
			data += items[i].name+'='+encodeURIComponent(items[i].value);
		}
	}

	return data;
}


function postComment() {
	if(getElement('checkSpellingButton').style.display == 'none') {
		commentSpell.resumeEditing();
		setTimeout("doComment();", 400);
	} else {
		doComment();
	}
}

function postCommentandVote() {
	getElement('alsoVotecheck').value = "on";
	postComment();
}

// COMMENT BOX

function toggleSpellButton() {
	if(getElement('checkSpellingButton').style.display == 'none') {
		getElement('checkSpellingButton').style.display = 'inline';
		getElement('resumeSpellingButton').style.display = 'none';
	} else {
		getElement('checkSpellingButton').style.display = 'none';
		getElement('resumeSpellingButton').style.display = 'inline';
	}
}

var commentSpell;

function placeSpellChecker (commentsTextDiv, commentsText) {
	var hideOnLoad = false; // the parent div is toggled instead of the textarea
	if (detect.OS == 'windows' && detect.browser == 'ie') {
		var tbwidth = '99%';
	} else {
		var tbwidth = '100%';
	}
	commentSpell = new ajaxSpell('commentSpell', tbwidth, '160', '/_util/spellcheck/broken-notebook-2.6/spell_checker.php', commentsTextDiv, commentsText, commentsText, '', '', hideOnLoad, showPreview);
} 

var edCanvas;
var urlsokay;
var hasBeenSubmitted;


function renderCommentBox (actionroot,imageroot,contentId,redirect,urlsokaypass,commentId, userDisplayName, userURL, groupId, friendListId, threadId, privateLabel, voted) {
urlsokay = urlsokaypass;
var commentfield ='';

window.onbeforeunload = leaveCommentConfirm;
hasBeenSubmitted = false;

commentfield += '<div class="commentbody user">';

if(userDisplayName && !userURL) {
	commentfield += '<div class="commentauthor">'+userDisplayName+' - Enter Your Comment:</div>';
} else if(userDisplayName) {
	commentfield += '<div class="commentauthor"><a href="'+userURL+'">'+userDisplayName+'</a> - Enter Your Comment:</div>';
} else {
	commentfield += '<div class="commentauthor">Leave a Comment:</div>';
}


commentfield += '<div class="commenttext">';

if (urlsokay == 1) {
	commentfield += '<div class="quicktags" id="qt_'+commentId+'"></div>';
	commentfield += '<div class="tagsallowed">(XHTML tags allowed - a,b,blockquote,br,code,dd,dl,dt,del,em,h2,h3,h4,i,ins,li,ol,p,pre,q,strong,ul)</div>';
}
if(vine.modules.content.comments.commentForm.showWordCount) {
	commentfield += '<div id="wordCountSpan">&nbsp;</div>';
}
commentfield += '<form id="commentsForm" method="post" action="'+actionroot+'/user/doComment" style="display: block; margin: 0 0 6px 0;">';
commentfield += '<input type="hidden" name="contentId" value="'+contentId+'" />';
commentfield += '<input type="hidden" name="groupId" value="'+groupId+'" />';
commentfield += '<input type="hidden" name="friendListId" value="'+friendListId+'" />';
commentfield += '<input type="hidden" name="threadId" value="'+threadId+'" />';
commentfield += '<input type="hidden" name="redirect" value="'+redirect+'" />';
commentfield += '<input type="hidden" name="parentId" value="'+commentId+'" />';
commentfield += '<input type="hidden" name="sendNotification" value="" />';
commentfield += '<input type="hidden" name="replyToId" value="" />';
commentfield += '<table class="commentform">';
if(!userDisplayName) { // unregistered user
	commentfield += '<tr><td><table cellpadding="4" cellspacing="0" border="0">';
	commentfield += '<tr><td><label for="commentName" style="font-weight: bold">Name: </label></td><td><input type="text" id="commentName" name="displayName" class="half flat" value="" /></td></tr>';
	commentfield += '<tr><td><label for="commentEmailAddress" style="font-weight: bold">Email Address (always private): </label></td><td><input type="text" id="commentEmailAddress" name="email" class="half flat" value="'+userURL+'" /></td></tr>';
	commentfield += '</table>';
	commentfield += '</td></tr>';
}
commentfield += '<tr><td>';
commentfield += '<div id="commentsTextDiv_'+commentId+'"></div>';
if(privateLabel) {
	commentfield += '<div style="background-color: #000; padding: 5px 10px 5px 10px; color: #fff; font-size: 10px; font-weight: bold"><img src="'+imageroot+'i_locked.gif" width="10" height="10" alt="" style="margin: 2px 7px 0 0" />You are posting this to the Private Discussion "'+privateLabel+'".</div>';
}
commentfield += '<div style="margin-top: 6px; width: 100%">';
if (voted == "10") { //1=can vote, 0=has voted  
	//use either checkbox or image (mike could change his mind)
	//commentfield += '<div id="alsoVote" style="font-size: 10px;margin: 6px 0 6px 0;"><input type="checkbox" name="alsoVote" checked="checked" style="width:auto" />Vote for this article upon submitting my comment (Voting helps move good articles up the Vine)</div>'; //old checkbox method
	commentfield += '<span id="alsoVote"><a id="postCommentAndVoteImage" href="javascript:void(postCommentandVote());" onClick="hasBeenSubmitted = true;" class="noborder"><img src="'+imageroot+'b_postcommentandvote.gif" style="margin-right:8px;"></a>';
	commentfield += '<a id="postingCommentAndVoteImage" style="display:none;" href="javascript:void(0);" class="noborder"><img src="'+imageroot+'b_postingandvote.gif" style="margin-right:8px;"></a>';
	commentfield += '<input type="hidden" id="alsoVotecheck" name="alsoVote" value="" /></span>';
}
commentfield += '<a id="postCommentImage" href="javascript:void(postComment())" onClick="hasBeenSubmitted = true;" class="noborder"><img src="'+imageroot+'b_postcomment.gif" style="margin-right:8px;"></a>';
commentfield += '<a id="postingCommentImage" style="display:none;" href="javascript:void(0);" class="noborder"><img src="'+imageroot+'b_posting.gif" style="margin-right:8px;"></a>';
commentfield += '<span id="checkSpellingButton"><a href="javascript:void(0);" class="noborder" onclick="toggleSpellButton();setCurrentObject(commentSpell); commentSpell.spellCheck();hasBeenSubmitted = true;"><img src="'+imageroot+'b_checkspelling.gif" style="margin-right:8px;"></a></span>';
commentfield += '<span id="resumeSpellingButton" style="display:none;"><a href="javascript:void(0);" class="noborder" onclick="toggleSpellButton();setCurrentObject(commentSpell); commentSpell.resumeEditing();hasBeenSubmitted = false;"><img src="'+imageroot+'b_resumeediting.gif" style="margin-right:8px;"></a></span>';
commentfield += '<span id="commentsText_'+commentId+'_spellMessage"></span>';
commentfield += '</div>';
//commentfield += '<div style="margin-top: 6px"><php echo $page->shell->whatsThis->icon(\'shield\'); ?></div>';
commentfield += '</td></tr></table>';
commentfield += '</form>';

commentfield += '<h3>Comment Preview:</h3>';
commentfield += '<div id="textDisplay"></div>';
commentfield += '</div></div>';

return commentfield;
}

function leaveCommentConfirm()
{
  	if (getElement('commentsText_'+currentCommentBox).value.length > 50 && !hasBeenSubmitted) //if greater than 50 chatacters, alert user
	  	return "If you leave now, you will abandon your comment.";
}

// JS QuickTags version 1.0
//
// Copyright (c) 2002-2004 Alex King
// http://www.alexking.org/
//
// Licensed under the LGPL license
// http://www.gnu.org/copyleft/lesser.html
//
// **********************************************************************
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
// **********************************************************************
//
// This JavaScript will insert the tags below at the cursor position in IE and 
// Gecko-based browsers (Mozilla, Camino, Firefox, Netscape). For browsers that 
// do not support inserting at the cursor position (Safari, OmniWeb) it appends
// the tags to the end of the content.
//
// The variable 'edCanvas' must be defined as the <textarea> element you want 
// to be editing in. See the accompanying 'index.html' page for an example.

var edButtons = new Array();
var edLinks = new Array();
var edOpenTags = new Array();

function edButton(id, display, tagStart, tagEnd, open) {
	this.id = id;				// used to name the toolbar button
	this.display = display;		// label on button
	this.tagStart = tagStart; 	// open tag
	this.tagEnd = tagEnd;		// close tag
	this.open = open;			// set to -1 if tag does not need to be closed
}

edButtons[edButtons.length] = new edButton('ed_bold'
                                          ,'Bold'
                                          ,'<strong>'
                                          ,'</strong>'
                                          );

edButtons[edButtons.length] = new edButton('ed_italic'
                                          ,'Italic'
                                          ,'<em>'
                                          ,'</em>'
                                          );

edButtons[edButtons.length] = new edButton('ed_block'
                                          ,'Quote'
                                          ,'<blockquote>'
                                          ,'</blockquote>'
                                          );

edButtons[edButtons.length] = new edButton('ed_link'
                                          ,'Link'
                                          ,''
                                          ,'</a>'
                                          ); // special case


function edLink(display, URL, newWin) {
	this.display = display;
	this.URL = URL;
	if (!newWin) {
		newWin = 0;
	}
	this.newWin = newWin;
}


edLinks[edLinks.length] = new edLink('alexking.org'
                                    ,'http://www.alexking.org/'
                                    );

edLinks[edLinks.length] = new edLink('tasks'
                                    ,'http://www.alexking.org/software/tasks/'
                                    );

edLinks[edLinks.length] = new edLink('photos'
                                    ,'http://www.alexking.org/software/photos/'
                                    );

function edShowButton(button, i) {
	var buttons = '';
	
	if (button.id == 'ed_img') {
		buttons += '<input type="button" id="' + button.id + '" class="ed_button" onclick="edInsertImage(edCanvas);" value="' + button.display + '" />';
	}
	else if (button.id == 'ed_link') {
		buttons += '<input type="button" id="' + button.id + '" class="ed_button" onclick="edInsertLink(edCanvas, ' + i + ');" value="' + button.display + '" />';
	}
	else {
		buttons += '<input type="button" id="' + button.id + '" class="ed_button" onclick="edInsertTag(edCanvas, ' + i + ');" value="' + button.display + '" />';
	}
	return buttons;
}

function edShowLinks() {
	var tempStr = '<select onchange="edQuickLink(this.options[this.selectedIndex].value, this);"><option value="-1" selected>(Quick Links)</option>';
	for (i = 0; i < edLinks.length; i++) {
		tempStr += '<option value="' + i + '">' + edLinks[i].display + '</option>';
	}
	tempStr += '</select>';
	document.write(tempStr);
}

function edAddTag(button) {
	if (edButtons[button].tagEnd != '') {
		edOpenTags[edOpenTags.length] = button;
		document.getElementById(edButtons[button].id).value = '/' + document.getElementById(edButtons[button].id).value;
	}
}

function edRemoveTag(button) {
	for (i = 0; i < edOpenTags.length; i++) {
		if (edOpenTags[i] == button) {
			edOpenTags.splice(i, 1);
			document.getElementById(edButtons[button].id).value = 		document.getElementById(edButtons[button].id).value.replace('/', '');
		}
	}
}

function edCheckOpenTags(button) {
	var tag = 0;
	for (i = 0; i < edOpenTags.length; i++) {
		if (edOpenTags[i] == button) {
			tag++;
		}
	}
	if (tag > 0) {
		return true; // tag found
	}
	else {
		return false; // tag not found
	}
}	

function edCloseAllTags() {
	var count = edOpenTags.length;
	for (o = 0; o < count; o++) {
		edInsertTag(edCanvas, edOpenTags[edOpenTags.length - 1]);
	}
}

function edQuickLink(i, thisSelect) {
	if (i > -1) {
		var newWin = '';
		if (edLinks[i].newWin == 1) {
			newWin = ' target="_blank"';
		}
		var tempStr = '<a href="' + edLinks[i].URL + '"' + newWin + '>' 
		            + edLinks[i].display
		            + '</a>';
		thisSelect.selectedIndex = 0;
		edInsertContent(edCanvas, tempStr);
	}
	else {
		thisSelect.selectedIndex = 0;
	}
}

function edToolbar() {
	var toolbar = '';
	toolbar += '<div id="ed_toolbar">';
	for (i = 0; i < edButtons.length; i++) {
		toolbar += edShowButton(edButtons[i], i);
	}
//	edShowLinks();
	toolbar += '</div>';
	return toolbar;
}

// insertion code

function edInsertTag(myField, i) {
	//IE support
	if (document.selection) {
		myField.focus();
	    sel = document.selection.createRange();
		if (sel.text.length > 0) {
			sel.text = edButtons[i].tagStart + sel.text + edButtons[i].tagEnd;
		}
		else {
			if (!edCheckOpenTags(i) || edButtons[i].tagEnd == '') {
				sel.text = edButtons[i].tagStart;
				edAddTag(i);
			}
			else {
				sel.text = edButtons[i].tagEnd;
				edRemoveTag(i);
			}
		}
		myField.focus();
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		var cursorPos = endPos;
		if (startPos != endPos) {
			myField.value = myField.value.substring(0, startPos)
			              + edButtons[i].tagStart
			              + myField.value.substring(startPos, endPos) 
			              + edButtons[i].tagEnd
			              + myField.value.substring(endPos, myField.value.length);
			cursorPos += edButtons[i].tagStart.length + edButtons[i].tagEnd.length;
		}
		else {
			if (!edCheckOpenTags(i) || edButtons[i].tagEnd == '') {
				myField.value = myField.value.substring(0, startPos) 
				              + edButtons[i].tagStart
				              + myField.value.substring(endPos, myField.value.length);
				edAddTag(i);
				cursorPos = startPos + edButtons[i].tagStart.length;
			}
			else {
				myField.value = myField.value.substring(0, startPos) 
				              + edButtons[i].tagEnd
				              + myField.value.substring(endPos, myField.value.length);
				edRemoveTag(i);
				cursorPos = startPos + edButtons[i].tagEnd.length;
			}
		}
		myField.focus();
		myField.selectionStart = cursorPos;
		myField.selectionEnd = cursorPos;
	}
	else {
		if (!edCheckOpenTags(i) || edButtons[i].tagEnd == '') {
			myField.value += edButtons[i].tagStart;
			edAddTag(i);
		}
		else {
			myField.value += edButtons[i].tagEnd;
			edRemoveTag(i);
		}
		myField.focus();
	}
}

function edInsertContent(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
		myField.focus();
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		              + myValue 
                      + myField.value.substring(endPos, myField.value.length);
		myField.focus();
		myField.selectionStart = startPos + myValue.length;
		myField.selectionEnd = startPos + myValue.length;
	} else {
		myField.value += myValue;
		myField.focus();
	}
}

function edInsertLink(myField, i, defaultValue) {
	if (!defaultValue) {
		defaultValue = 'http://';
	}
	if (!edCheckOpenTags(i)) {
		var URL = prompt('Enter the URL' ,defaultValue);
		if (URL) {
			edButtons[i].tagStart = '<a href="' + URL + '">';
			edInsertTag(myField, i);
		}
	}
	else {
		edInsertTag(myField, i);
	}
}

function removeTags(s) {
	if (s) return s.replace(/<[^>]+>/g,'');
	else return null;
}



