// $Id: util.js,v 1.49 2011-08-04 11:57:09 jrixon Exp $

function get_cookie(name)
{
	var dc     = document.cookie.split(';');
	var prefix = name + "=";
	for(var i = 0; i < dc.length; i++) {
		if(dc[i].indexOf(prefix) != -1) {
			return unescape(dc[i].substring(dc[i].indexOf(prefix) + prefix.length));
		}
	}

	return null;

}



function set_cookie(name, value, expires, path, domain, secure)
{
	value = escape(value);
	value = stripBadUTF8(value);

	_set_cookie(name, value, expires, path, domain, secure);
}



function set_cookie_no_escape(name, value, expires, path, domain, secure)
{
	_set_cookie(name, value, expires, path, domain, secure);
}


function _set_cookie(name, value, expires, path, domain, secure)
{
	var curCookie = name + "=" + value +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");

	if (document.useCookieFix) {
		// AIR is using the cookieFix method
		window.parentSandboxBridge.setCookie(curCookie);
	}
	else {
		// normal method, set the cookie directly
		document.cookie = curCookie;
	}
}

if (document.ELEMENT_NODE == null) {
	document.ELEMENT_NODE = 1;
	document.TEXT_NODE = 3;
}



function getTextValue(el)
{
	var i, s;
	s = "";
	try {
		for (i = 0; i < el.childNodes.length; i++) {
			if (el.childNodes[i].nodeType == document.TEXT_NODE) {
				s += el.childNodes[i].nodeValue;
			}
			else if (
				(el.childNodes[i].nodeType == document.ELEMENT_NODE) &&
				(el.childNodes[i].tagName == "BR")
			) {
				s += " ";
			}
			else {
				s += getTextValue(el.childNodes[i]);
			}
		}
	} catch(err){ }

	return normalizeString(s);
}

var whtSpEnds=new RegExp("^\\s*|\\s*$", "g");
var whtSpMult=new RegExp("\\s\\s+", "g");



function normalizeString(s)
{
	s = s.replace(whtSpMult, " ");
	s = s.replace(whtSpEnds, "");
	return s;
}



function _f_sort(_a, _b)
{
	var a = _a.val;
	var b = _b.val;
	return a < b ? -1 : a > b ? 1 : 0;
}



function padNum(num, size)
{
	var d = num.indexOf('.'),
	num_zeros;

	if(d == -1) d = num.length;

	if((num_zeros = size - d) <= 0) return num;

	for(var i = 0, new_num = []; i < num_zeros; i++) new_num[i] = '0';
	new_num[i] = num;

	return new_num.join('');
}



// decode a value from a cookie (convert +s to spaces etc)
function decodeCookieVal(val)
{
	if (val) {
		return val.replace(/\+/g, ' ');
	}
	else {
		return '';
	}
}


// encode a cookie
function encodeCookieVal(val)
{
	if (val) {
		return val.replace(/\+/g, "%2B");
	}
	else {
		return '';
	}
}




function oneYearFromNow()
{
	var expires = new Date();
	expires.setFullYear(expires.getFullYear() + 1);
	return expires;
}



function getBaseURL(type)
{
	var url;

	if(document.isHTTPS) {
		if(type == 'dirty') {
			url = document.dirty_scgiURL;
		} else if(type == 'hist') {
			url = document.hist_scgiURL;
		} else if (type == 'err') {
			url = document.err_scgiURL;
		} else {
			url = document.scgiURL;
		}
	} else {
		if(type == 'dirty') {
			url = document.dirty_cgiURL;
		} else if(type == 'hist') {
			url = document.hist_cgiURL;
		} else if (type == 'err') {
			url = document.err_cgiURL;
		} else {
			url = document.cgiURL;
		}
	}

	return url;
}



/* Remove bad utf8 chars (namely the %u.... for unknown characters)
 */
function stripBadUTF8(text)
{
	return text.replace(new RegExp(/%u[0-9A-Fa-f]{4}/g), '');
}



function limit_type_desc(_v)
{
	switch (_v) {
		case 'N': return 'No Limit';
		case 'P': return 'Pot Limit';
		case 'F': return 'Fixed Limit';
	}
	return '';
}



function game_code_desc(_v, _select)
{
	switch (_v) {
	case 'HOLDEM':
		return 'Hold\'em';
	case 'OMAHA':
		return 'Omaha';
	case 'OMAHA_HILO':
		return ['Omaha Hi',
				typeof _select !== 'boolean' || _select ? ' ' : '&nbsp;',
				'Lo'].join('');
	}
	return '';
}



function game_def_id_desc(_v, _select)
{
	var desc = '';
	if (document.game_def_code) {
		desc = game_code_desc(document.game_def_code[_v], _select);
	}
	return desc;
}



/* Removes all event handling functions from a node and
 * of all its child nodes. This function should be used for
 * resolving cycle references on IE 6/7. Just call it before
 * removeChild or innerHTML. Taken from Douglas
 * Crockford's website
 *
 * Hm maybe we should do a check for the browser and prototype a wrapper
 * for removeChild and innerHTML
 */
function purge(d)
{
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}



/* Parse JSON
 *
 *   _json   - JSON to parse
 *   returns - parsed json
 */
function parse_json(_json)
{
	if(typeof _json !== 'string' || !_json.length) return null;

	if(window.JSON && window.JSON.parse) {
		return window.JSON.parse(str_trim_lt(_json));
	}

	// Defined in json2.js
	if(typeof JSON !== 'undefined' && typeof JSON.parse === 'function') {
		return JSON.parse(str_trim_lt(json));
	}

	warnfire('making call to eval()');
	return eval(['(', _json, ')'].join(''));
};



/* The preferred function to trim a string (leading and trailing chars)
 *
 * _src - string to trim
 * _delim - character to trim (expects a single character)
 *
 * returns - trimmed string
 */
function str_trim_lt(_src, _delim)
{
	var len = _src.length,
	i, c, last;

	if(typeof _delim === 'undefined' || _delim === null || !_delim.length) _delim = ' ';

	// trim from left
	for(i = 0; i < len; i++) {
		c = _src.charAt(i);
		if(_delim !== c) {
			// substring only if necessary
			if(i !== 0) _src = _src.substring(i);
			break;
		}
	}

	// found at least one instance of non-delimiter character
	if(i < len) {
		// trim from right
		last = _src.length - 1;
		for(i = last; i > -1; i--) {
			c = _src.charAt(i);
			if(_delim !== c) {
				// substring only if necessary
				if(i !== last) _src = _src.substring(0, i + 1);
				break;
			}
		}
	}

	// string is empty or made of delimiting characters - return empty
	else {
		_src = '';
	}

	return _src;
}



/* Private function to decompress a base64 number (prefixed with !)
 *
 *   val      - value to decompress
 *   returns  - decompressed value
 */
function decompress_num(val)
{
	var n = [],
	base64_exp = /^!([0-9a-zA-Z+/]+)(.*)$/,
	str_exp = /^([^!]*)(.*)$/,
	m;

	while(val.length) {

		// is base64 number or just '!'
		if(val.charAt(0) === '!') {
			m = val.match(base64_exp);
			if(m && m.length == 3) {
				n[n.length] = base64_to_dec(m[1]);
				val = m[2];
			}
			else {
				n[n.length] = '!';
				val = val.substring(1);
			}
		}

		// get all the chars up to next base64 or end-of-string
		else {
			m = val.match(str_exp);
			if(m &&	m.length == 3) {
				n[n.length] = m[1];
				val = m[2];
			}
			else {
				throw ['Illegal number: \'', val, '\''].join('');
			}
		}
	}

	return n.join('');
}



/* Private function to convert a base64 number to decimal
 *
 *   val      - base64 value to convert
 *   returns  - decimal value
 */
function base64_to_dec(val)
{
	var n = 0,
	i = 0,
	l = val.length,
	base64 = document.base64;

	for(; i < l; i++) {
		if(val.charAt(i) === '!') continue;
		n = n * 64 + base64.indexOf(val.charAt(i));
	}

	return n;
};

document.base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';


