/*
	util.js contains useful functions to be used by other parts of javascript
	in the backend of Colony
*/

function URLEncode (clearString) {
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
			x += match[1].length;
		} else {
			if (clearString[x] == ' ')
				output += '+';
			else {
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
			}
			x++;
		}
	}
	return output;
}

function showhidecookie( el, strCookieName ) {
    if ( typeof( el ) == 'string' ) { var el = $(el); }
    if ( showhide( el ) == "shown" ) {
        AddToCookieArray( el.id, strCookieName );
        return "shown";
    } else {
        RemoveFromCookieArray( el.id, strCookieName );
		return "hidden";
    }
}

function AddToCookieArray( strLayerID, strCookieName )
{
	var strCookie = Cookie.get( strCookieName );
	if ( !strCookie ) { strCookie = "" };
    var arrElements = strCookie.split( "," );
    if ( !arrElements.contains( strLayerID ) ) { arrElements.push( strLayerID );}
	Cookie.set( strCookieName, arrElements.toString(), {duration: 1});
}
	
function RemoveFromCookieArray( strLayerID, strCookieName )
{
    var strCookie = Cookie.get( strCookieName );
	if ( !strCookie ) { strCookie = "" };
	var arrElements = strCookie.split( "," );
	arrElements.remove( strLayerID );
	Cookie.set( strCookieName, arrElements.toString(), {duration: 1});
}

function isNumeric(x) {
    var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
    var result = x.match(RegExp);
    return result;
}

// The hide() method sets an elements display property to none
function hide( el ) {
	if ( typeof( el ) == 'string' ) { var el = $(el); }
	if ( el ) { el.setStyle("display", "none"); }
}

// The show() method sets an elements display property to block
function show( el ) {
    if ( typeof( el ) == 'string' ) { var el = $(el); }
	if ( el ) { el.style.display = 'block'; }
}

function showhide( el ) {
    if ( typeof( el ) == 'string' ) { var el = $(el); }
	if ( el ) {
		if ( el.style.display == 'none' ) {
			show( el );
			return "shown";
		} else {
			hide( el );
			return "hidden";
		}
	}
}

