/*function centerDiv(div,obj){
	//alert('centerDiv('+div+')');
	if(!$(div)){
		//alert('!'+div);
		return;
	}
	var w = $(div).offsetWidth;//parseInt($(div).style.width.replace('px',''));
	var h = $(div).offsetHeight;//parseInt($(div).style.height.replace('px',''));
	if(obj){
		var pw = obj.pageWidth()-20;
	}else{
		var pw = pageWidth()-20;
	}
	if(obj){
		var ph = obj.pageHeight()-50;
	}else{
		var ph = pageHeight()-50;
	}
	
	
	
	$(div).style.position = 'absolute';
	$(div).style.left = Math.floor((pw/2)-(w/2))+'px';
	$(div).style.top = Math.floor((ph/2)-(h/2))+'px';
}*/

function empty(string){
	if(string==''){
		return true;
	}else{
		return false;
	}
}

function redirect(url){
	if(parent){
		if(parent.parent){
			if(parent.parent.parent){
				if(parent.parent.parent.parent){
					parent.parent.parent.parent.location.href = url;
				}else{
					parent.parent.parent.location.href = url;
				}
			}else{
				parent.parent.location.href = url;
			}
		}else{
			parent.location.href = url;
		}
	}else{
		document.location.href = url;
	}
}

function evaljson(response){
	if(typeof moofix == 'function'){
		var loaded = moofix(eval("("+response+")"));
	}else{
		var loaded = eval("("+response+")");	
	}
	if(loaded && isset(loaded['abort'])){
		redirect(loaded['abort']);
		return 'Session Time Out';
	}
	
	return loaded;
}	

function ucwords(str) {
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();
    });
}
function noBubble(ev){
    if (window.event) {
        event.returnValue=false;
        event.cancelBubble=true;
    }	else       {
        ev.preventDefault();
        ev.stopPropagation();
    }
    return false;
}

function eval_r(response){
	while(stristr(response,":[],")){
		response = response.replace(":[],",":{},");
	}
	return eval("(" + response + ")");
}

function pullvars(string){
	var vars = false;
	string = string+'';
	while(matched = string.match(/\{\$([^\}]*)\}/i)){
		if(!vars){
			vars = {};
		}
		vars[matched[0]] = matched[1];
		string = string.replace(matched[0],matched[1]);
	}
	return vars;
}

function sanitize(obj){
	obj = clone(obj);
	for(var o in obj){
		if(typeof obj[o] != 'string' && typeof obj[o]!='number'){
			delete obj[o];
		}
	}
	return obj;
	
	//Menus.alert(hint,typeof obj);
	if(typeof obj=='object'){
		var obj = {};
		for(var o in obj){
			var check = sanitize(obj[o]);
			if(check != 'nogo'){
				obj[o]=check;
			}else{
				delete obj[o];
			}
		}
		return obj;
	}else if(typeof obj=='number' || typeof obj =='string'){
		return obj;
	}
	return 'nogo';
}

function rand(min,max){
	max = max+min;
	return Math.floor(Math.random()*max+1)+min;
}

function explode(delimiter,string){
	var array = {};
	string = string+'';
	var splitted = string.split(delimiter);
	var key = 0;
	for(var s in splitted){
		if(stristr(string,splitted[s])){
			array[key++]=splitted[s];
		}else{
			break;
		}
	}
	return array;
}

function joinobj(delimiter,obj){
	var string = '';
	var key = 0;
	for(var o in obj){
		if(key>0){
			string = string+delimiter+obj[o];
		}else{
			string = obj[o];
		}
		key++;
	}
	return string;
}


function in_array(find,array){
	for(var i in array){
		if(i==find || array[i]==find){
			return true;
		}
	}
	return false;
}

function is_array(input){
	return typeof(input)=='object';//&&(input instanceof Array);
}

function is_null(input){
	return typeof(input)=='null';//&&(input instanceof Array);
}

function push(obj,val){
	for(var i=0; i<=1000; i++){
		if(!isset(obj[i])){
			obj[i]=clone(val);
			break;
		}
	}
	return obj;
}


function clone(obj){
	return eval(obj.toSource());
}


function $( id )
{
    if (document.getElementById)
        var returnVar = document.getElementById(id);
    else if (document.all)
        var returnVar = document.all[id];
    else if (document.layers)
        var returnVar = document.layers[id];
    return returnVar;
}

//function $(id) { return document.getElementById(id); }

function stristr(haystack,needle){
	
	if((haystack+'').indexOf(needle) == -1){
		return false;
	}else{
		return true;
	}
}
function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}
	

function trim(stringToTrim) {
	return (stringToTrim+'').replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return (stringToTrim+'').replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return (stringToTrim+'').replace(/\s+$/,"");
}


function deldiv(div){
	var DIVtoRemove = document.getElementById(div);
	DIVtoRemove.parentNode.removeChild(DIVtoRemove);
}
function changeiframe(iframe,url){
	window.frames[iframe].location.href=url;
}
function getiframe(iframe){
	return window.frames[iframe].location.href;
}
function writeiframe(iframe,html){
	window.frames[iframe].document.body.innerHTML = html;
}

function ask(message, url)
{
	if(confirm(message) )
	{
		parent.location.href = url;
	}
}

function Set_Cookie( 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 GET(varible) {
	var url = document.location + '';
	q=url.split('?');
	if (q[1]) {
	var pairs = q[1].split('&');
	for (i=0;i<pairs.length;i++) {
	var keyval = pairs[i].split('=');
	if (keyval[0] == varible) {
	var squareid = keyval[1];
	}	}	}	
	return squareid;
}
// this function gets the cookie, if it exists
function Get_Cookie( 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 ) );
}

//this fixes an issue with the old method, ambiguous values
//with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


	// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function isset(test){
	if(test+"" == "undefined"){
		return false;
	}else{
		return true;
	}
}
function include(src)
{
	var script = document.createElement("SCRIPT");
	script.type = "text/javascript";
	document.getElementsByTagName("body")[0].appendChild(script);
	script.src = src;
}

function showndiv(id) {
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		if(document.getElementById(id).style.display!='none'){
			return true;
		}else{
			return false;
		}
	}
	else {
		if (document.layers) { // Netscape 4
			if(document.id.display!='none'){
				return true;
			}else{
				return false;
			}
		}
		else { // IE 4
			if(document.all.id.style.display!='none'){
				return true;
			}else{
				return false;
			}
		}
	}
}

function hidediv(id) {
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		//if(document.getElementById(id)){
			if(!document.getElementById(id)){
				alert('!'+id);
				return;
			}
		
			document.getElementById(id).style.display = 'none';
		//}
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}
function showdiv(id) {
	//safe function to show an element with a specified id
		  
	if (document.getElementById) { // DOM3 = IE5, NS6
		//if(document.getElementById(id)){
		if(!document.getElementById(id)){
			alert('!'+id);
			return;
		}
			document.getElementById(id).style.display = 'block';
		//}
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}
function writit(text,id)
{
	if(typeof text =="undefined")
		text = '';
		
	if (document.getElementById)
	{
		x = document.getElementById(id);
		x.innerHTML = '';
		x.innerHTML = text;
	}
	else if (document.all)
	{
		x = document.all[id];
		x.innerHTML = text;
	}
	else if (document.layers)
	{
		x = document.layers[id];
		text2 = '<P CLASS="testclass">' + text + '</P>';
		x.document.open();
		x.document.write(text2);
		x.document.close();
	}
}
function appendit(text,id)
{
	if (document.getElementById)
	{
		x = document.getElementById(id);
		//x.innerHTML = '';
		x.innerHTML = x.innerHTML+text;
	}
	else if (document.all)
	{
		x = document.all[id];
		x.innerHTML =  x.innerHTML+text;
	}
	else if (document.layers)
	{
		x = document.layers[id];
		//text2 = '<P CLASS="testclass">' + text + '</P>';
		x.document.open();
		x.document.write(text2);
		x.document.close();
	}
}

var http_request = false;
function ajax(url, parameters,callback,arg1,arg2,arg3) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
       http_request = new XMLHttpRequest();
       if (http_request.overrideMimeType) {
       	// set type accordingly to anticipated content type
          //http_request.overrideMimeType('text/xml');
          http_request.overrideMimeType('text/html');
       }
    } else if (window.ActiveXObject) { // IE
       try {
          http_request = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
          try {
             http_request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {}
       }
    }
    if (!http_request) {
       //alert('Cannot create XMLHTTP instance');
       return false;
    }
    
    http_request.onreadystatechange = function alertContents() {
		if (http_request.readyState == 4) {
		        if (http_request.status == 200) {
		           //alert(http_request.responseText);
		           result = http_request.responseText;
		           if(typeof callback != "undefined"){
				   		if(typeof arg3!="undefined"){
				   			eval(callback+"(result,'"+arg1+"','"+arg2+"','"+arg3+"')");
				   		}else if(typeof arg2 !="undefined"){
				   			eval(callback+"(result,'"+arg1+"','"+arg2+"')");
				   		}else if(typeof arg1 !="undefined"){
				   			eval(callback+"(result,'"+arg1+"')");
				   		}else{
				   			eval(callback+"(result)");
				   		}
		           }
		          // say(result)//document.getElementById('myspan').innerHTML = result;            
		        } else {
		           //alert('There was a problem with the request.');
		        }
		     }
		};
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
}

function pageWidth() {
	return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
} 
function pageHeight() {
	return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
} 
function posLeft() {
	return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}
function posTop() {
	return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}
function posRight() {return posLeft()+pageWidth();} 
function posBottom() {return posTop()+pageHeight();}
    
	
	
function moveDiv(id,x,y){
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.position = "absolute";
		document.getElementById(id).style.top = y;
		document.getElementById(id).style.left = x;
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.position = "absolute";
			document.id.top = y;
			document.id.left = x;				
		}
		else { // IE 4
			document.all.id.style.position = "absolute";
			document.all.id.style.top = y;
			document.all.id.style.left = x;				
		}
	}	
}

function centerCoords(width,height){
	coords = Array();
	coords["x"]=(pageWidth()/2)+posLeft()-(width/2);
	coords["y"]=(pageHeight()/2)+posTop()-(height/2);
	return coords;
}
function resizeElement (id,width,height) {

	var i = document.getElementById(id);
	i.style.height = height + 'px';
	i.style.width = width + 'px';
}

function getMouseXY(e) {
	if (event) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	}else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}  
	if (tempX < 0){tempX = 0;}
	if (tempY < 0){tempY = 0;}  
	var xy;
	xy["x"] = tempX;
	xy["y"] = tempY;
	
	//document.Show.MouseX.value = tempX;
	//document.Show.MouseY.value = tempY;
	return xy;
}
function print_r(theObj,indent){
	if(typeof theObj =='null'){
		return 'null';
	}
    var output="\n";
    if (indent == undefined) { indent = "	"; } else { indent += "	"; }
    if(theObj.constructor == Array || theObj.constructor == Object) {
      for(var p in theObj){
        if(theObj[p].constructor == Array|| theObj[p].constructor == Object){
            var type = (theObj[p].constructor == Array) ? "Array" : "Object";
            output += indent+"["+p+"]("+type+")=>\n";
            output += print_r(theObj[p],indent);
        } else { output += indent+"["+p+"]:"+theObj[p]+"\n"; }
      }
    }
    return output;
} 
function alert_r(hint,obj){
	if(typeof(obj)=="undefined"){
		obj = hint;
		hint = "alert_r";
	}
	alert(hint+":"+print_r(obj));
}

function isset(obj){
	if(typeof obj == "undefined"){
		return false;
	}{
		return true;
	}
}
function unset(obj){
	delete obj;
	
}


function get_html_translation_table (table, quote_style) {
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        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;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

function htmlentities (string, quote_style) {
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}


function getAttribute(div,name,isdiv){
	var values = {};
	if(!isdiv){
		var div = $(div);
	}
	if(name=='tag'){
		return div.nodeType;
	}
	for (var x = 0; x < div.attributes.length; x++) {
		if( div.attributes[x].nodeName == name){
			return div.attributes[x].nodeValue;
		}
		values[div.attributes[x].nodeName] = div.attributes[x].nodeValue
	}
	if(!name){
		return values;
	}
	return false;	
}
function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
    
    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);
    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};
function parseColorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    
    if((color+'').indexOf('rgb')==-1){
    	return (color+'').replace(' none repeat scroll 0% 0%','');
    }
    
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
    
    
    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);
    return '#'+RGBtoHex(red,green,blue).toUpperCase();
};

function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}
function toHex(N) {
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16)
      + "0123456789ABCDEF".charAt(N%16);
}

function strip_tags (input, allowed) {
   allowed = (((allowed || "") + "")
      .toLowerCase()
      .match(/<[a-z][a-z0-9]*>/g) || [])
      .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
   var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
       commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
   return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
      return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
   });
}

function time () {
    return Math.floor(new Date().getTime()/1000);
}

function date(format, timestamp) {
    var that = this,
        jsdate, f, formatChr = /\\?([a-z])/gi, formatChrCb,
        // Keep this here (works, but for code commented-out
        // below for file size reasons)
        //, tal= [],
        _pad = function (n, c) {
            if ((n = n + "").length < c) {
                return new Array((++c) - n.length).join("0") + n;
            } else {
                return n;
            }
        },
        txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur",
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"],
        txt_ordin = {
            1: "st",
            2: "nd",
            3: "rd",
            21: "st", 
            22: "nd",
            23: "rd",
            31: "st"
        };
    formatChrCb = function (t, s) {
        return f[t] ? f[t]() : s;
    };
    f = {
    // Day
        d: function () { // Day of month w/leading 0; 01..31
            return _pad(f.j(), 2);
        },
        D: function () { // Shorthand day name; Mon...Sun
            return f.l().slice(0, 3);
        },
        j: function () { // Day of month; 1..31
            return jsdate.getDate();
        },
        l: function () { // Full day name; Monday...Sunday
            return txt_words[f.w()] + 'day';
        },
        N: function () { // ISO-8601 day of week; 1[Mon]..7[Sun]
            return f.w() || 7;
        },
        S: function () { // Ordinal suffix for day of month; st, nd, rd, th
            return txt_ordin[f.j()] || 'th';
        },
        w: function () { // Day of week; 0[Sun]..6[Sat]
            return jsdate.getDay();
        },
        z: function () { // Day of year; 0..365
            var a = new Date(f.Y(), f.n() - 1, f.j()),
                b = new Date(f.Y(), 0, 1);
            return Math.round((a - b) / 864e5) + 1;
        },

    // Week
        W: function () { // ISO-8601 week number
            var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
                b = new Date(a.getFullYear(), 0, 4);
            return 1 + Math.round((a - b) / 864e5 / 7);
        },

    // Month
        F: function () { // Full month name; January...December
            return txt_words[6 + f.n()];
        },
        m: function () { // Month w/leading 0; 01...12
            return _pad(f.n(), 2);
        },
        M: function () { // Shorthand month name; Jan...Dec
            return f.F().slice(0, 3);
        },
        n: function () { // Month; 1...12
            return jsdate.getMonth() + 1;
        },
        t: function () { // Days in month; 28...31
            return (new Date(f.Y(), f.n(), 0)).getDate();
        },

    // Year
        L: function () { // Is leap year?; 0 or 1
            return new Date(f.Y(), 1, 29).getMonth() === 1 | 0;
        },
        o: function () { // ISO-8601 year
            var n = f.n(), W = f.W(), Y = f.Y();
            return Y + (n === 12 && W < 9 ? -1 : n === 1 && W > 9);
        },
        Y: function () { // Full year; e.g. 1980...2010
            return jsdate.getFullYear();
        },
        y: function () { // Last two digits of year; 00...99
            return (f.Y() + "").slice(-2);
        },

    // Time
        a: function () { // am or pm
            return jsdate.getHours() > 11 ? "pm" : "am";
        },
        A: function () { // AM or PM
            return f.a().toUpperCase();
        },
        B: function () { // Swatch Internet time; 000..999
            var H = jsdate.getUTCHours() * 36e2, // Hours
                i = jsdate.getUTCMinutes() * 60, // Minutes
                s = jsdate.getUTCSeconds(); // Seconds
            return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
        },
        g: function () { // 12-Hours; 1..12
            return f.G() % 12 || 12;
        },
        G: function () { // 24-Hours; 0..23
            return jsdate.getHours();
        },
        h: function () { // 12-Hours w/leading 0; 01..12
            return _pad(f.g(), 2);
        },
        H: function () { // 24-Hours w/leading 0; 00..23
            return _pad(f.G(), 2);
        },
        i: function () { // Minutes w/leading 0; 00..59
            return _pad(jsdate.getMinutes(), 2);
        },
        s: function () { // Seconds w/leading 0; 00..59
            return _pad(jsdate.getSeconds(), 2);
        },
        u: function () { // Microseconds; 000000-999000
            return _pad(jsdate.getMilliseconds() * 1000, 6);
        },

    // Timezone
        e: function () { // Timezone identifier; e.g. Atlantic/Azores, ...
// The following works, but requires inclusion of the very large
// timezone_abbreviations_list() function.
/*              return this.date_default_timezone_get();
*/
            throw 'Not supported (see source code of date() for timezone on how to add support)';
        },
        I: function () { // DST observed?; 0 or 1
            // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
            // If they are not equal, then DST is observed.
            var a = new Date(f.Y(), 0), // Jan 1
                c = Date.UTC(f.Y(), 0), // Jan 1 UTC
                b = new Date(f.Y(), 6), // Jul 1
                d = Date.UTC(f.Y(), 6); // Jul 1 UTC
            return 0 + ((a - c) !== (b - d));
        },
        O: function () { // Difference to GMT in hour format; e.g. +0200
            var a = jsdate.getTimezoneOffset();
            return (a > 0 ? "-" : "+") + _pad(Math.abs(a / 60 * 100), 4);
        },
        P: function () { // Difference to GMT w/colon; e.g. +02:00
            var O = f.O();
            return (O.substr(0, 3) + ":" + O.substr(3, 2));
        },
        T: function () { // Timezone abbreviation; e.g. EST, MDT, ...
            return 'UTC';
        },
        Z: function () { // Timezone offset in seconds (-43200...50400)
            return -jsdate.getTimezoneOffset() * 60;
        },

    // Full Date/Time
        c: function () { // ISO-8601 date.
            return 'Y-m-d\\Th:i:sP'.replace(formatChr, formatChrCb);
        },
        r: function () { // RFC 2822
            return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
        },
        U: function () { // Seconds since UNIX epoch
            return jsdate.getTime() / 1000 | 0;
        }
    };
    this.date = function (format, timestamp) {
        that = this;
        jsdate = (
            (typeof timestamp === 'undefined') ? new Date() : // Not provided
            (timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
            new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
        );
        return format.replace(formatChr, formatChrCb);
    };
    return this.date(format, timestamp);
}
function setDropdown(div,value,title){
	if(!title){
		var title = value;
	}
	//this.alert(div+'='+value);
	if($(div).selectedIndex>=0){
		$(div).value = value;
		var append = true;
		for (var i = 0; i < $(div).options.length; i++) {
			var val = $(div).options[i].value;
			if(val == value){
				$(div).options[i].selected = true;
				$(div).selectedIndex = i;
				append = false;
				break;
			}
		}
		if(append){
			$(div).innerHTML = $(div).innerHTML +'<option selected="selected" value="'+value+'">'+title+'</option>';
		}
		$(div).value = value;
		return true;
	}else{
		return false;
	}
};

