/* Reference Article:
Dustin Diaz:
http://www.dustindiaz.com/top-ten-javascript/
*/

/* addEvent: simplified event attachment */
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
	
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

/* window 'load' attachment */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

/* grab Elements from the DOM by className */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/* toggle an element's display */
function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

/* insert an element after a particular node */
function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

/* Array prototype, matches value in array: returns bool */
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

/* get, set, and delete cookies */
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
	
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
	
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function AllowOnlyNumeric(e,str,field) {

	// Get the ASCII value of the key that the user entered
	var keyPressed;
	
	if(window.event)
		keyPressed = window.event.keyCode; // IE
	else
		keyPressed = e.which; // standard

	//alert(keyPressed);
	// Verify if the key entered was a numeric character (0-9) or a decimal (.)
	if ( (keyPressed > 47 && keyPressed < 58) || keyPressed == 46 || keyPressed == 8 )
		//If it was, then allow the entry to continue
		return true;
	else
		// If it was not, then dispose the key and continue with entry
		//window.event.returnValue = null;
		e.preventDefault();
		
}

function sumChars(str,field,next) {

	var total = 0;
	//alert(str);
	for (i=0; i < str.length; i++) {
		//alert(str[i]);
		var num = parseInt(str.charAt(i));
		if(isNaN(num) == false) { total = total + num;}
	}
	//alert(total);
	document.getElementById(field).innerHTML = total;
	//document.forms['scorecard'].elements[field].value = total;

	if(str.length == 9) document.forms.scorecard[next].focus();
}

function checkCount(str,field) {

	if(str.length == 9) 
		return true;
	else
		alert("You must enter scores for all 9 holes");
		document.forms.scorecard[field].focus();
}

/*
MS Word cleaner function
CRJB October 15, 2009
*/
var swapCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...");  
function cleanWordClipboard(input) {
    // debug for new codes
    // for (i = 0; i < input.length; i++)  alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
    
    var output = input;
    for (i = 0; i < swapCodes.length; i++) {
        var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
        output = output.replace(swapper, swapStrings[i]);
    }
    return output;
}

/*
 HTML use example:

<script language="Javascript">word-to-plain-text.js</script>

<form name="wordCleaner" onsubmit="return false;">
<textarea style="width: 480px; height: 100px" id="wordInput">&bull; &ldquo;Double Quotes&rdquo;,
&bull; &lsquo;Single quotes&rsquo;, 
&bull; Ellipsis &hellip;,
&bull; en-dash &ndash;</textarea><br />

<button onClick="wordInput.value = cleanWordClipboard(wordInput.value)">Clean</button>
</form>

*/