function is_msie()
{
    var m = navigator.userAgent.match(/MSIE (\d+(\.\d+)?)/);
    if (navigator.userAgent.indexOf('Opera') == -1 && m)
        return parseFloat(m[1]);
    else
        return 0;
}

function is_opera()
{
    var m = navigator.userAgent.match(/Opera.(\d+(\.\d+)?)/);
    return m ? parseFloat(m[1]) : 0;
}

function is_mozilla()
{
    var m = navigator.userAgent.match(/Gecko/),
        m1 = navigator.userAgent.match(/AppleWebKit/);
    return m && !m1 ? 1 : 0;
}

function is_webkit()
{
    var m = navigator.userAgent.match(/AppleWebKit/);
    return m ? 1 : 0;
}

function setCookie(name, value, expires, path, domain, secure)
{
    // set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());
	
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	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() : "") + 
	((path) ? ";path=" + path : "") + 
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
}

function getCookie(name)
{
    var srch = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(srch);
        if (offset != -1) {
            offset += srch.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) {
                end = document.cookie.length;
            }
            return unescape(document.cookie.substring(offset, end));
        }
    }
}

function showCookieError()
{
    if (!navigator.cookieEnabled) {
        alert('This feature requires cookies to be enabled in your browser. Please enable cookies ' +
        'and try again.');
    }
}

var quirksMode = !document.compatMode || document.compatMode == 'BackCompat';

function getClientWidth()
{
    return !quirksMode ? document.documentElement.clientWidth : document.body.clientWidth;
}

function getClientHeight()
{
    return !quirksMode ? document.documentElement.clientHeight : document.body.clientHeight;
}

function getScrollLeft()
{
    return !quirksMode ? 
    	document.documentElement.scrollLeft :
    	document.body.scrollLeft;
}

function getScrollTop()
{
    return !quirksMode ? 
    	document.documentElement.scrollTop :
    	document.body.scrollTop;
}

function getScrollWidth()
{
    return !quirksMode ? 
    	document.documentElement.scrollWidth :
    	document.body.scrollWidth;
}

function getScrollHeight()
{
    return !quirksMode ? 
    	document.documentElement.scrollHeight :
    	document.body.scrollHeight;
}

function scrollTo(sl, st)
{
	if (!quirksMode) {
		document.documentElement.scrollLeft = sl;
		document.documentElement.scrollTop = st;
	} else {
		document.body.scrollLeft = sl;
		document.body.scrollTop = st;
	}
}

function getControlPixelPos(e, ofs_x, ofs_y, w, h, pad, fixedPos)
{
    var l = ofs_x ? ofs_x: 0;
    var t = ofs_y ? ofs_y: 0;
    var ctl = e;
    if (!pad) pad = 0;

    if (e.getBoundingClientRect) {
    	var br = e.getBoundingClientRect();
    	l += br.left;
    	t += br.top;
    	if (!fixedPos) {
	    	l += getScrollLeft();
	    	t += getScrollTop();
    	}
    } else {
	    while (e && e.tagName != 'BODY') {
	        var p = e.offsetParent;
	        l += e.offsetLeft;
	        t += e.offsetTop;
	        l -= p && p.tagName != 'BODY' ? p.scrollLeft : 0;
	        t -= p && p.tagName != 'BODY' ? p.scrollTop : 0;
	        e = p;
	    }
	    if (fixedPos) {
	    	l -= getScrollLeft();
	    	t -= getScrollTop();
	    }
    }
    if (w > 0 && h > 0) {
        var sl = fixedPos ? 0 : getScrollLeft();
        var st = fixedPos ? 0 : getScrollTop();
        if (l > getClientWidth()+sl-w-pad-1) {
            l += ctl.offsetWidth-w;
            if (l > getClientWidth()+sl-w-pad-1) {
                l = getClientWidth()+sl-w-pad-1;
            }
            if (l < sl+pad+1) {
            	l = sl+pad+1;
           	}
        }
        if (t > getClientHeight()+st-h-pad-1) {
            t = getClientHeight()+st-h-pad-1;
        }
        if (t < st+pad+1) {
        	t = st+pad+1;
       	}
    }
    return new Array(l, t);
}


function trim(str, chars) 
{
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function __getComputedStyle(element, style)
{
	var computedStyle;
	if (typeof element.currentStyle != 'undefined') {
		computedStyle = element.currentStyle; 
	} else { 
		computedStyle = document.defaultView.getComputedStyle(element, null); 
	}
	return computedStyle[style];
}

function valueFilter(e, forbidden) 
{ 
    var skip = false, 
        e = e || window.event, 
        key = String.fromCharCode(e.which || e.keyCode); 
 
    for (var i=0; i<forbidden.length; i++) { 
        if(String(forbidden[i]) === key.toLowerCase()) { 
            skip = true; 
            break; 
        } 
    } 
    if (skip) { 
        if(e.preventDefault) e.preventDefault(); 
        e.returnValue = false; 
    } 
    return true; 
} 

function valueFilterAllowed(e, allowed) 
{ 
    var skip = true, 
        e = e || window.event, 
        key = String.fromCharCode(e.which || e.keyCode);
    if ((e.which || e.keyCode) == 8 || (e.which || e.keyCode) == 9 ||
        ((e.which || e.keyCode) >= 35 && (e.which || e.keyCode) <= 40)) 
        return true;
    for (var i=0; i<allowed.length; i++) {
        if(String(allowed[i]) === key.toLowerCase()) { 
            skip = false; 
            break; 
        } 
    } 

    if (skip) { 
        if (e.preventDefault) e.preventDefault(); 
        e.returnValue = false; 
    } 
    return true;  
}

function disable(el, dis)
{
	el.disabled = dis ? true : false;
	el.style.backgroundColor = dis ? '#D4D0C8' : '';
}

hiddenElements = [];
function hideElementsByType(hideIn, showIn, tagname)
{
    var topObjPos = hideIn ? getObjPosition(hideIn) : null;
    var ctls = document.getElementsByTagName(tagname);
    for (var i = 0; i < ctls.length; i++) {
        var ctlPos = getObjPosition(ctls[i]);
        if (!topObjPos || (topObjPos.left <= ctlPos.right && 
            ctlPos.left <= topObjPos.right && 
            topObjPos.top <= ctlPos.bottom && 
            ctlPos.top <= topObjPos.bottom) &&
            ctls[i].style.visibility != 'hidden')
        {
            ctls[i].style.visibility = 'hidden';
            hiddenElements.push(ctls[i]);
        }
    }
    if (showIn) {
        var ctls = showIn.getElementsByTagName(tagname);
        for (i = 0; i < ctls.length; i++) { 
            ctls[i].style.visibility = 'visible';
        }
    }
}

function hideElements(hideIn, showIn)
{
    if (is_msie() && is_msie() < 7) {
        hideElementsByType(hideIn, showIn, 'SELECT');
    }
    hideElementsByType(hideIn, showIn, 'OBJECT');
    hideElementsByType(hideIn, showIn, 'EMBED');
}

function showElements() 
{
    if (document.getElementById('popupFadeBack') && 
        document.getElementById('popupFadeBack').style.display == '' ) return;
    for (var i = 0; i < hiddenElements.length; i++) {
        hiddenElements[i].style.visibility = 'visible';
    }
    hiddenElements = [];
}

function getObjPosition(obj) 
{ 
    var pos = getControlPixelPos(obj, 0, 0, 0, 0, 0);     
    return { left: pos[0], top: pos[1], 
        right: pos[0]+obj.offsetWidth, bottom: pos[1]+obj.offsetHeight, 
        width: obj.offsetWidth, height: obj.offsetHeight }; 
} 

function addWindowOnLoad(fnc)
{
    if (is_msie()) {
        window.attachEvent('onload', fnc);
    } else {
        window.addEventListener('load', fnc, false);
    }
}

// localStorage 
function putToLocalStorage(key, oValue, domain)
{
	if (typeof(localStorage) != "undefined") {
		var lStorage = localStorage[domain?domain:location.hostname];
		lStorage.setItem(key, toJson(oValue));
	} else {
        throw 'LocalStorage is not supported';
    }
}

function getFromLocalStorage(key, domain)
{
	if (typeof(localStorage) != "undefined") {
	   var lStorage = localStorage[domain?domain:location.hostname];
	   return lStorage.getItem(key);
	} else {
    	throw 'LocalStorage is not supported';
    }
}
function isLocalStorageAvailable()
{
	return (typeof(localStorage) != "undefined");
}

function putToSessionStorage(key, oValue)
{
	if (typeof(sessionStorage) != "undefined") {
        var sStorage = sessionStorage;
        sStorage.setItem(key, toJson(oValue));
    } else {
        throw 'SessionStorage is not supported';
    }
}

function getFromSessionStorage(key, domain)
{
    if (typeof(sessionStorage) != "undefined"){
        var sStorage = sessionStorage;
       return sStorage.getItem(key);
    } else {
        throw 'SessionStorage is not supported';
    }
}
function isSessionStorageAvailable()
{
    return (typeof(sessionStorage) != "undefined" && sessionStorage != null);
}

function putToGlobalStorage(key, oValue, domain)
{
    if (typeof(globalStorage) != "undefined") {
        var gStorage = globalStorage[domain?domain:location.hostname];
        gStorage.setItem(key, toJson(oValue));
    } else {
        throw 'GlobalStorage is not supported';
    }
}

function getFromGlobalStorage(key, domain)
{
    if (typeof(globalStorage) != "undefined") {
       var gStorage = globalStorage[domain?domain:location.hostname];
       return gStorage.getItem(key);
    } else {
        throw 'GlobalStorage is not supported';
    }
}
function isGlobalStorageAvailable()
{
    return (typeof(globalStorage) != "undefined");
}

function putToUserDataStorage(key, oValue)
{
    if (document.getElementById('storageElement') != "undefined") {
         putToUserData(key, toJson(oValue));
    } else {
        throw 'userData is not supported';
    }
}

function getFromUserDataStorage(key)
{
    if (document.getElementById('storageElement') != "undefined") {       
       return getFromUserData(key);
    } else {
        throw 'userData is not supported';
    }
}
function isUserDataStorageAvailable()
{
    return (is_msie() >= 5 && is_msie() <= 7 && document.getElementById('storageElement') != "undefined");
}

function toJson(item) 
{
	if (typeof (item.toJson) == 'function') 
       return item.toJson();
	
	var out = '';
    if (typeof(item) == 'number') {
        out = item.toString();
    } else if (typeof(item) == 'boolean') {
        out = item ? 'true' : 'false';
    } else if (typeof(item) == 'object') {
        var first = true;
        if (item.length != 'undefined') {
            // numeric array
            out = '[';
            for (var k = 0; k < item.length; k++) {
                if (!first) out += ', ';
                first = false;
                out += toJson(item[k]);
            }
            out += ']';
        } else {
            // hash
            out = '{';
            for (k1 in item) {
                if (!first) out += ', ';
                first = false;
                out +=  '"' + toJson(k1) + '": ' + toJson(item[k1]);
            }
            out += '}';
        }
    } else {
        // assume a string
        out = quote(item);

    }
    return out;
}

var escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
    meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            };


function quote(string) {
	// If the string contains no control characters, no quote characters, and no
	// backslash characters, then we can safely slap some quotes around it.
	// Otherwise we must also replace the offending characters with safe escape
	// sequences.
    escapeable.lastIndex = 0;
    return escapeable.test(string) ?
        '"' + string.replace(escapeable, function (a) {
            var c = meta[a];
            if (typeof c === 'string') {
                return c;
            }
            return '\\u' + ('0000' +
                    (+(a.charCodeAt(0))).toString(16)).slice(-4);
        }) + '"' :
        '"' + string + '"';
}


// client side storage for ie 5-7
function initUserData()
{
	if (is_msie() >= 5 && is_msie() <= 7) {
		storage = document.getElementById('userDataStorage');
		if (!storage.addBehavior) {
			throw new 'userData is not available';
		} else {
			storage.addBehavior("#default#userData");
			storage.load("userDataStorage");
		}
		return true;
	}
	return false;
}

function putToUserData(sKey, sValue) {
	if (typeof(storage) == "undefined" && initUserData() == false) return;
    storage.setAttribute(sKey, sValue);
    storage.save("userDataStorage");
}
 
function getFromUserData(sKey) {
	if (typeof(storage) == "undefined" && initUserData() == false) return ''; 
    return storage.getAttribute(sKey);
}
 
function removeFromUserData(sKey) {
	if (typeof(storage) == "undefined" && initUserData() == false) return;
    storage.removeAttribute(sKey);
    storage.save("userDataStorage");
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
 
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
 
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38']  = '&amp;';
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

function html_entity_decode( string, quote_style ) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
 
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
 
    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';
 
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function addHandler(object, event, handler)
{
  if (typeof object.addEventListener != 'undefined')
    object.addEventListener(event, handler, false);
  else if (typeof object.attachEvent != 'undefined')
    object.attachEvent('on' + event, handler);
  else
    throw "Incompatible browser";
}

function removeHandler(object, event, handler)
{
  if (typeof object.removeEventListener != 'undefined')
    object.removeEventListener(event, handler, false);
  else if (typeof object.detachEvent != 'undefined')
    object.detachEvent('on' + event, handler);
  else
    throw "Incompatible browser";
}

function getXmlHttpRequest()
{
	var req = null;
	if (window.XMLHttpRequest) {
	    req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
	    try {
	        req = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
	        try {
	            req = new ActiveXObject("Microsoft.XMLHTTP");
	        } catch (e) {
	            req = null;
	        }
	    }
	}
    return req;
}

function sendRequest(url, useJsTag)
{
    if (!useJsTag) {
        var xmlHttp = getXmlHttpRequest();
        if (xmlHttp) {
    	    xmlHttp.open("GET", url, true);
    	    xmlHttp.send(null);
        }
    } else {
        var s = document.getElementById('__ajaxScriptTag__');
        if (s) s.parentNode.removeChild(s);
        s = document.createElement('script');
        s.id = '__ajaxScriptTag__';
        var head = document.getElementsByTagName('head')[0];
        if (head) head.appendChild(s);
        s.src = url;
    }
}

String.prototype.toBool = function() {
	return (/^true|1$/i).test(this);
}

// TODO: replace with Array.prototype.indexOf
function array_indexof(array, val) 
{
    for (var i = 0, l = array.length; i < l; i++) {
        if (array[i] == val) {
            return i;
        }
    }
    return -1;
}

// TODO: replace with Array.prototype.unique
function array_unique(array) 
{
    // original by: Carlos R. L. Rodrigues
    var p, i, j;
    for(i = array.length; i;){
        for(p = --i; p > 0;){
            if(array[i] === array[--p]){
                for(j = p; --p && array[i] === array[p];);
                i -= array.splice(p + 1, j - p).length;
            }
        }
    }
    return true;
}

/**
 * A class to parse color values
 * @author Stoyan Stefanov <sstoo@gmail.com>
 * @link   http://www.phpied.com/rgb-color-parser-in-javascript/
 * @license Use it if you like it
 */
function RGBColor(color_string)
{
    this.ok = false;
    color_string = color_string.replace(/"/g,'');
    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // before getting into regexps, try simple matches
    // and overwrite the input
    var simple_colors = {
        aliceblue: 'f0f8ff',
        antiquewhite: 'faebd7',
        aqua: '00ffff',
        aquamarine: '7fffd4',
        azure: 'f0ffff',
        beige: 'f5f5dc',
        bisque: 'ffe4c4',
        black: '000000',
        blanchedalmond: 'ffebcd',
        blue: '0000ff',
        blueviolet: '8a2be2',
        brown: 'a52a2a',
        burlywood: 'deb887',
        cadetblue: '5f9ea0',
        chartreuse: '7fff00',
        chocolate: 'd2691e',
        coral: 'ff7f50',
        cornflowerblue: '6495ed',
        cornsilk: 'fff8dc',
        crimson: 'dc143c',
        cyan: '00ffff',
        darkblue: '00008b',
        darkcyan: '008b8b',
        darkgoldenrod: 'b8860b',
        darkgray: 'a9a9a9',
        darkgreen: '006400',
        darkkhaki: 'bdb76b',
        darkmagenta: '8b008b',
        darkolivegreen: '556b2f',
        darkorange: 'ff8c00',
        darkorchid: '9932cc',
        darkred: '8b0000',
        darksalmon: 'e9967a',
        darkseagreen: '8fbc8f',
        darkslateblue: '483d8b',
        darkslategray: '2f4f4f',
        darkturquoise: '00ced1',
        darkviolet: '9400d3',
        deeppink: 'ff1493',
        deepskyblue: '00bfff',
        dimgray: '696969',
        dodgerblue: '1e90ff',
        feldspar: 'd19275',
        firebrick: 'b22222',
        floralwhite: 'fffaf0',
        forestgreen: '228b22',
        fuchsia: 'ff00ff',
        gainsboro: 'dcdcdc',
        ghostwhite: 'f8f8ff',
        gold: 'ffd700',
        goldenrod: 'daa520',
        gray: '808080',
        green: '008000',
        greenyellow: 'adff2f',
        honeydew: 'f0fff0',
        hotpink: 'ff69b4',
        indianred : 'cd5c5c',
        indigo : '4b0082',
        ivory: 'fffff0',
        khaki: 'f0e68c',
        lavender: 'e6e6fa',
        lavenderblush: 'fff0f5',
        lawngreen: '7cfc00',
        lemonchiffon: 'fffacd',
        lightblue: 'add8e6',
        lightcoral: 'f08080',
        lightcyan: 'e0ffff',
        lightgoldenrodyellow: 'fafad2',
        lightgrey: 'd3d3d3',
        lightgreen: '90ee90',
        lightpink: 'ffb6c1',
        lightsalmon: 'ffa07a',
        lightseagreen: '20b2aa',
        lightskyblue: '87cefa',
        lightslateblue: '8470ff',
        lightslategray: '778899',
        lightsteelblue: 'b0c4de',
        lightyellow: 'ffffe0',
        lime: '00ff00',
        limegreen: '32cd32',
        linen: 'faf0e6',
        magenta: 'ff00ff',
        maroon: '800000',
        mediumaquamarine: '66cdaa',
        mediumblue: '0000cd',
        mediumorchid: 'ba55d3',
        mediumpurple: '9370d8',
        mediumseagreen: '3cb371',
        mediumslateblue: '7b68ee',
        mediumspringgreen: '00fa9a',
        mediumturquoise: '48d1cc',
        mediumvioletred: 'c71585',
        midnightblue: '191970',
        mintcream: 'f5fffa',
        mistyrose: 'ffe4e1',
        moccasin: 'ffe4b5',
        navajowhite: 'ffdead',
        navy: '000080',
        oldlace: 'fdf5e6',
        olive: '808000',
        olivedrab: '6b8e23',
        orange: 'ffa500',
        orangered: 'ff4500',
        orchid: 'da70d6',
        palegoldenrod: 'eee8aa',
        palegreen: '98fb98',
        paleturquoise: 'afeeee',
        palevioletred: 'd87093',
        papayawhip: 'ffefd5',
        peachpuff: 'ffdab9',
        peru: 'cd853f',
        pink: 'ffc0cb',
        plum: 'dda0dd',
        powderblue: 'b0e0e6',
        purple: '800080',
        red: 'ff0000',
        rosybrown: 'bc8f8f',
        royalblue: '4169e1',
        saddlebrown: '8b4513',
        salmon: 'fa8072',
        sandybrown: 'f4a460',
        seagreen: '2e8b57',
        seashell: 'fff5ee',
        sienna: 'a0522d',
        silver: 'c0c0c0',
        skyblue: '87ceeb',
        slateblue: '6a5acd',
        slategray: '708090',
        snow: 'fffafa',
        springgreen: '00ff7f',
        steelblue: '4682b4',
        tan: 'd2b48c',
        teal: '008080',
        thistle: 'd8bfd8',
        tomato: 'ff6347',
        turquoise: '40e0d0',
        violet: 'ee82ee',
        violetred: 'd02090',
        wheat: 'f5deb3',
        white: 'ffffff',
        whitesmoke: 'f5f5f5',
        yellow: 'ffff00',
        yellowgreen: '9acd32'
    };
    for (var key in simple_colors) {
        if (color_string == key) {
            color_string = simple_colors[key];
        }
    }
    // emd of simple type-in colors

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }

}
