/*


Kinetics ajax/dhtml framework funcitons
Copyright® Kinetics Multimedia (www.kinetics.com.br)

*/




/**
*
*  base64 encode / decode
*  http://www.webtoolkit.info/
*
**/


var ie=document.all;
var firefox=false;
var chrome=false;
var safari=false;
var nn6=document.getElementById&&!document.all;
var nn6off = nn6 ? 2 : 0;

var base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}




function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
            
    var histogram = {}, tmp_arr = [];
	try{
	 var ret = str.toString();
	}
	catch( e )
	{
		var ret = str;
	}
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}
function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    

    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}
function addslashes(str) {
	if(str==null)
	return;
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\0/g,'\\0');
return str;
}
function stripslashes(str) {
if(str==null)
	return;
str=str.replace(/\\'/g,'\'');
str=str.replace(/\\"/g,'"');
str=str.replace(/\\0/g,'\0');
str=str.replace(/\\\\/g,'\\');
return str;
}
function fademessage(str)
{
	infobubble(str, 300);
}
function warning(str)
{
	alert(str);
}
function is_array( mixed_var ) 
{
    return ( mixed_var instanceof Array );
}
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
/**
* Esta função simula a função print_r do PHP
*
*
* @param {Array} input Array ou objeto 
* @param {string} _indent Variável de sistema, usada pala própria função
* @return {String} Uma String que simula a função print_r do PHP
*/
function print_r( input, _indent )
{
     // Recuo
     
     var indent            =    ( typeof( _indent ) == 'string' ) ? _indent + '    ' : '    '
     var parent_indent    =    ( typeof( _indent ) == 'string' ) ? _indent : '';
     
     var output            =    '';
     
     // Tipo de Elemento do Array
     
     switch( typeof( input ) )
     {
         case 'string':
             output        =    "'" + input + "'";
         break;
         
         case 'number':
             output        =    input + "";
         break;
                 
         case 'boolean':
             output        =    ( input ? 'true' : 'false' ) + "";
         break;
         
         case 'object':
             output        =    ( ( input.reverse ) ? 'Array ' : 'Object' ) + "";
     
             output       +=    parent_indent + "(";
             
             for( var i in input )
             {
                 output +=    indent + '[' + i + '] => ' + print_r( input[ i ], indent );
             }
             
             output       +=    parent_indent + " )"
         break;
     }
     
     return output;
}
/**
* Esta função simula a função serialize do PHP
*<br>Retornando dados neste padrão. Facilita a integração Javascript->PHP, já que o PHP consegue receber os dados a partir da função unserialize.
*
*
* @param {Array} a Array ou objeto 
* @return {String} Uma String que simula a função serialize do PHP
*/
function serialize(a)
{
	var serializedString = '';
	var arrayLength = 0;
	for(var aKey in a)
	{
		//key definition
		if(aKey * 1 == aKey) //is_numeric?
		{
			//integer keys look like i:key
			serializedString += 'i:' + aKey + ';';	
		}
		else
		{
			//string keys look like s:key_length:key;
			serializedString += 's:' + aKey.length + ':"' + aKey + '";';
		}
		
		//value definition
		if(a[aKey] * 1 == a[aKey])
		{
			//integer value look like i:value
			serializedString += 'i:' + a[aKey] + ';';	
		}
		else if(typeof(a[aKey]) == "string")
		{
			//string value look like s:key_length:value;
			serializedString += 's:' + a[aKey].length + ':"' + a[aKey] + '";';
		}
		else if(a[aKey] instanceof Array)
		{
			serializedString += serialize(a[aKey]);
		}
		arrayLength++;
	}
	serializedString = 'a:' + arrayLength + ':{' + serializedString + '}';
	
	return serializedString;
}

/**Função que converte um valor do formato monetário para um valor float
*
*
* @param {String} moeda Valor em formato monetário
* @return {float} Valor em Float
*/
function moeda2float(moeda)
{
	moeda = moeda.replace(/\,/g,"");
	moeda = moeda.replace(".",",");
	moeda = parseFloat(moeda);
	return moeda;
}
/**Função que converte um valor float para um valor em formato monetário
*
*
* @param {float} num Valor em Float
* @return {String} Valor em formato monetário
*/
function float2moeda(num)
{
	x = 0;

	if(num<0) {
	num = Math.abs(num);
	x = 1;
	} if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);

	num = Math.floor((num*100+0.5)/100).toString();

	if(cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','
	+num.substring(num.length-(4*i+3)); ret = num + '.' + cents; if (x == 1) ret = ' - ' + ret;return ret;

}
 
var isdrag=false;
var x,y;
var dobj;

var ie=document.all;
var ff=!ie;

function utf8(wide) {
  var c, s;
  var enc = "";
  var i = 0;
  while(i<wide.length) {
    c= wide.charCodeAt(i++);
    // handle UTF-16 surrogates
    if (c>=0xDC00 && c<0xE000) continue;
    if (c>=0xD800 && c<0xDC00) {
      if (i>=wide.length) continue;
      s= wide.charCodeAt(i++);
      if (s<0xDC00 || c>=0xDE00) continue;
      c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
    }
    // output value
    if (c<0x80) enc += String.fromCharCode(c);
    else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
    else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
    else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
  }
  return enc;
}


function clearloads()
{
	abort_all_ajax_requests();
	if( ckidle_timer ) clearTimeout( ckidle_timer );
}

// shortname to getElementById
function $( s ) { return document.getElementById( s ); }

// shortname to createElement
function ce( t ) { return document.createElement( t ); }

// void function
function v(){};

// insert node AFTER some dom element
function insertAfter(node, referenceNode)
{
  referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
}
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
function isfunction(variable)
{
    return (typeof(variable) == "function")?  true: false;
}

function isdefined( variable)
{
    return (typeof(variable) == "undefined")?  false: true;
}

function isobject( variable)
{
    return (typeof(variable) == "object")?  false: true;
}

function isnumber( variable)
{
    return (typeof(variable) == "number")?  false: true;
}
function isstring( variable)
{
    return (typeof(variable) == "string")?  false: true;
}

// Returns the value of a string
function val( o )
{
	var vo = o*1;
	return vo+'' == 'NaN' ? 0 : vo;
}

// sprintf
function sprintf()
{
   if (!arguments || arguments.length < 1 || !RegExp)
   {
      return;
   }
   var str = arguments[0];
   var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
   var a = b = [], numSubstitutions = 0, numMatches = 0;
   while (a = re.exec(str))
   {
      var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
      var pPrecision = a[5], pType = a[6], rightPart = a[7];

      numMatches++;
      if (pType == '%')
      {
         subst = '%';
      }
      else
      {
         numSubstitutions++;
         if (numSubstitutions >= arguments.length)
         {
            alert('Error! Not enough function arguments (' + (arguments.length - 1)
               + ', excluding the string)\n'
               + 'for the number of substitution parameters in string ('
               + numSubstitutions + ' so far).');
         }
         var param = arguments[numSubstitutions];
         var pad = '';
                if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
           else if (pPad) pad = pPad;
         var justifyRight = true;
                if (pJustify && pJustify === "-") justifyRight = false;
         var minLength = -1;
                if (pMinLength) minLength = parseInt(pMinLength);
         var precision = -1;
                if (pPrecision && pType == 'f')
                   precision = parseInt(pPrecision.substring(1));
         var subst = param;
         switch (pType)
         {
         case 'b':
            subst = parseInt(param).toString(2);
            break;
         case 'c':
            subst = String.fromCharCode(parseInt(param));
            break;
         case 'd':
            subst = parseInt(param) ? parseInt(param) : 0;
            break;
         case 'u':
            subst = Math.abs(param);
            break;
         case 'f':
			if( precision > -1 )
			 {
				subst = Math.round(parseFloat(param) * Math.pow(10, precision)) + '';
				if( subst == '0' )	for( var i = 0 ; i < precision ; i++ ) subst += '0'; 
				subst  = subst.substr( 0, subst.length-2 ) + '.' + subst.substr( subst.length-2, 1000 );
			 }
			 else
				 subst = parseFloat(param);
            break;
         case 'o':
            subst = parseInt(param).toString(8);
            break;
         case 's':
            subst = param;
            break;
         case 'x':
            subst = ('' + parseInt(param).toString(16)).toLowerCase();
            break;
         case 'X':
            subst = ('' + parseInt(param).toString(16)).toUpperCase();
            break;
         }
         var padLeft = minLength - subst.toString().length;
         if (padLeft > 0)
         {
            var arrTmp = new Array(padLeft+1);
            var padding = arrTmp.join(pad?pad:" ");
         }
         else
         {
            var padding = "";
         }
      }
      str = leftpart + padding + subst + rightPart;
   }
   return str;
}


// Inspect function will open a new window with all variables/object contained by any object
function inspect_old( dobj )
{
	win = window.open( '', 'inspectwindow' );
	for (var i in dobj)	
	{ 
		var j = eval( 'dobj.' + i );
		win.document.write( i + ', ' + typeof( j )+ ', ' +  j + '<br>' );
//		debug( i, typeof( j ), j );
	}
}


// Inspect function will open a new window with all variables/object contained by any object
var inspectObjLine = [];
function inspect( dobj, nohtml )
{
//	win = window.open( '', 'inspectwindow' );
	debugclose();
	inspectObjLine = [];
	for (var i in dobj)	
	{ 
		if( nohtml == true && i.match( /(inner|outer)/ ) ) continue;
		try
		{
			var j = eval( 'dobj.' + i );
		}
		catch( e )
		{
			try
			{
				var j = eval( 'dobj[' + i + ']' );
			}
			catch( e )
			{
				continue;
			}
		}
		s = j + '';
		s = s.replace( /</g, '&lt;' );
		s = s.replace( />/g, '&gt;' );
		if( typeof( j ) == 'object' )
		{
			var idx = inspectObjLine.length;
			inspectObjLine.push( j );
			s = '<a href="#" onclick="inspect(inspectObjLine[' + idx + '])"><b>' + s + '</b></a>';
		}

//		win.document.write( i + ', ' + typeof( j )+ ', ' +  j + '<br>' );
		debug( i, typeof( j ), s );
	}
}


// write a floating DHTML debug window with variable parameters
function debug()
{
	var i;
	var list = [];

	if( $('log') == null )
	{
		log = ce( 'div' );
		log.id = 'log';
		log.className = 'debug';
		log.innerHTML = '<nobr><b>Debug Window</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:debugclose()">close</a></nobr>';
		document.body.appendChild( log );
	}

	for( i = 0 ; i < arguments.length ; i++ )
	{
		list[i] = arguments[i];
	}
	$('log').innerHTML += '<br>' + list.join( ', ' );
	$('log').style.zIndex = 1000000;
	$('log').style.top = document.body.scrollTop + 10;
}


// close debug window
function debugclose()
{
	var _log = $('log');
	if( _log == null ) return;
	_log.parentNode.removeChild( _log );
	_log = null;
}

function imgmaxrectcenter( img, width, height )
{
	if( !isdefined( width ) ) return;
	if( !isdefined( height ) ) return;
	if( !isdefined( img.tim ) ) img.tim = 0;
	if( img.tim < 10 && (img.width == 0 || img.clientWidth <= 0 ) )
	{
		img.tim++;
		setTimeout( function() { imgmaxrectcenter( img, width, height ); }, img.tim * 20 + 1 );
		return;
	}
	imgmaxrect( img, width, height );
	img.style.position = 'relative';
	img.style.left = Math.floor( (width-img.clientWidth)/2 );
	img.style.top = Math.floor( (height-img.clientHeight)/2 );
}

function imgmaxrect(img, width, height)
{
	if( !isdefined( width ) ) return;
	if( !isdefined( height ) ) return
	if( !isdefined( img.tim ) ) img.tim = 0;
	if( img.tim < 10 && (img.width == 0 || img.clientWidth <= 0 ) )
	{
		
		img.tim++;
		setTimeout( function() { imgmaxrect( img, width, height ); }, img.tim * 20 + 1 );
		return;
	}
	var r = 1;
	if( !isdefined( img.nheight ) )
	{
		img.nheight = img.height;
		img.nwidth = img.width;
	}
	var w = img.nwidth;
	var h = img.nheight;
	
	if( w == -1 )
	{
		debug( 'reload', img.width );
		setTimeout( function() { imgmaxrect( img, width, height ) }, img.tim * 20 + 1 );
		return;
	}

	if (width<w || height<h)
	{
		var mh= height/h;
		var mw= width/w;
		if(mh>mw)  r=mw; else  r=mh;
	}

	img.style.width = w = Math.floor( w*r );
	img.style.height = h = Math.floor( h*r );

	img.style.marginLeft = 0;
	img.style.marginTop = 0;
	var o = img.parentNode;
	if( typeof( o ) == 'Object' )
	{
		while( o != document.body && o.parentNode != null && o.onmouseover == null ) o = o.parentNode;
		if( isdefined( o.onmouseover ) ) o.title = img.title;
	}
	img.isloaded = true;
}




function getCSSValue( o, v )
{
	if( o == null || !isdefined( o.style ) ) return '';
	if( !ie )
	{
		var cs = document.defaultView.getComputedStyle( o, null );
		return cs[v];
//		v = v.replace(/[A-Z]/g,"-$&").toLowerCase();
//		return o.style.getPropertyValue(v);
	}
	else
		return o.currentStyle[v];
}

function getCSSValueNum( o, v )
{
	r = parseInt(getCSSValue(o,v));
	if( isNaN(r) ) r = 0;
	return r;
}


function saveCSSValues( o, vs )
{
	var arr = vs.split(',');
	o.saveCSS = new Object;
	for( var i = 0 ; i < arr.length ; i++ )
		o.saveCSS[arr[i]] = getCSSValue( o, arr[i] );
}

function restoreCSSValues( o )
{
	for (var v in o.saveCSS)
		o.style[v] = o.saveCSS[v];
}

function getHeight( o )
{
	if( o == null ) return 0;
	var bt = getCSSValueNum( o, 'borderTopWidth' );
	var bb = getCSSValueNum( o, 'borderBottomWidth' );
	if( bt == 0 ) o.style.borderTop = '1px solid red';
	if( bb == 0 ) o.style.borderBottom = '1px solid red';
	var h = o.offsetHeight;
	if( bt == 0 )
	{
		o.style.borderTop = '';
		h--;
	}
	if( bb == 0 )
	{
		o.style.borderBottom = '';
		h--;
	}
	if( !ie )
	{
		if( bt > 0 ) h -= bt;
		if( bb > 0 ) h -= bb;
		var pt = getCSSValueNum( o, 'paddingTop' );
		var pb = getCSSValueNum( o, 'paddingBottom' );
		if( pt > 0 ) h -= pt;
		if( pb > 0 ) h -= pb;
	}
	if( h < 0 ) h = 0;
	return h;
}


function getWidth( o )
{
	if( o == null ) return 0;
	var bl = getCSSValueNum( o, 'borderLeftWidth' );
	var br = getCSSValueNum( o, 'borderRightWidth' );
	if( bl == 0 ) o.style.borderLeft = '1px solid red';
	if( br == 0 ) o.style.borderRight = '1px solid red';
	var w = o.offsetWidth;
	if( bl == 0 )
	{
		o.style.borderLeft = '';
		if( !ie ) w--;
	}
	if( br == 0 )
	{
		o.style.borderRight = '';
		if( !ie ) w--;
	}
	if( !ie )
	{
		if( bl > 0 ) w -= bl;
		if( br > 0 ) w -= br;
		var pl = getCSSValueNum( o, 'paddingLeft' );
		var pr = getCSSValueNum( o, 'paddingRight' );
		if( pl > 0 ) w -= pl;
		if( pr > 0 ) w -= pr;
	}
	if( v < 0 ) v = 0;
	return w;
}

loadurl_ani = true;
loadurl_a_speed = 300;

function loadurl_a( obj, s, h, ds, dh, t, repeat )
{
	var anirepeat;
	if( isdefined( obj.a_time ) && obj.a_time > 0 )
	{
		var now = new Date().getTime();
		if( !isdefined( repeat ) )
		{
			var delay = now - obj.a_time;
			anirepeat = Math.floor( delay/t )-1;
		}
		else
		{
			anirepeat = --repeat;
		}
	}
	if( anirepeat < 0 ) anirepeat = 0;
	s += ds;
	if( dh != 0 )
	{
		h += dh;
		obj.style.height = h;
		obj.style.overflow = 'hidden';
	}
	if( s >= 1 )
	{
		obj.style.opacity = '';
		obj.style.filter = '';
		obj.style.height = '';
//		if( obj.sw == 0 ) obj.style.width = '';
		obj.style.overflow = obj.so;
		obj.tid = null;
		obj.a_time = 0;
		return;
	}
	if( s <= 0 )
	{
		obj.style.opacity = '';
		obj.style.filter = '';
		obj.loading();
		obj.tid = null;
		obj.a_time = 0;
		return;
	}
	else
	{
		obj.style.opacity = s;
		obj.style.filter = 'progid:DXImageTransform.Microsoft.alpha(opacity=' + Math.floor(s*100) + ')';
	}
	obj.a_time = new Date().getTime();
	if( anirepeat > 0 )
		loadurl_a( obj, s, h, ds, dh, t, anirepeat );
	else
		obj.tid = setTimeout( function() { loadurl_a( obj, s, h, ds, dh, t ); }, t );
}

function getloadwin( o )
{
	while( o != null && !isdefined( o.loadurl ) ) o = o.parentNode;
	return o;
}


function loadurl( url, obj, ani, speed )
{
	var w = getWidth( obj );
	obj.url = url;
	obj.loadurl = 1;
	var steps = 10;
	var h = getHeight( obj );
	if( h < 30 ) h = 30;
	obj.sh = getCSSValueNum(obj,'height');
	obj.sw = getCSSValueNum(obj,'width');
	obj.so = getCSSValue(obj,'overflow');

	if( isdefined(obj.tid) && obj.tid != null )
	{
		clearTimeout(obj.tid);
		obj.style.opacity = '';
		obj.style.filter = '';
		obj.innerHTML = '';
		obj.tid = null;
		obj.a_time = 0;
	}

	function resultload( txt, obj )
	{
		if( ani && obj.tid != null ) clearTimeout( obj.tid );
		resultform( txt, obj );
		obj.style.height = '';
//		if( obj.sw == 0 ) obj.style.width = '';
		obj.style.overflow = obj.so;
		if( ani )
		{
			var newh = getHeight( obj );
			var dh = newh > 10 ? (newh-h)/steps : 0;
			loadurl_a( obj, 0, h, 1/steps, dh, speed/steps );
		}
	}

	obj.loading = function ()
	{
		obj.innerHTML = '<div class="loading">&nbsp;</div>';
		if( obj.sh == 0 ) obj.style.height = h;
//		if( obj.sw == 0 && w > 30 ) obj.style.width = w;
		obj.style.overflow = 'hidden';
		watch_animate( obj, -2 );
	}

	obj.reload = function()
	{
		loadurl( nocache(url), obj );
	}

	if( !isdefined(ani) ) ani = loadurl_ani;
	if( !isdefined(speed) ) speed = loadurl_a_speed;
	nobubble();
	if( obj.innerHTML > '' && ani )
		loadurl_a( obj, 1, h, -1/steps, 0, speed/steps );
	else
	{
		obj.loading();
		obj.style.height = '';
	}
	ajaxrequest( url, resultload, obj, 0 );
}

// recise and center vert/horiz one image to max
function imgmaxdimmiddle( img, max )
{
	if( !isdefined( max ) ) return;
	if( !isdefined( img.tim ) ) img.tim = 0;
	if( img.tim < 10 && (img.width == 0 || img.clientWidth <= 0 ) )
	{
		img.tim++;
		setTimeout( function() { imgmaxdimmiddle( img, max ); }, img.tim * 20 + 1 );
		return;
	}
	imgmaxdim( img, max );
	img.style.position = 'relative';
	img.style.left = Math.floor( (max-img.clientWidth)/2 );
}

// recise and center horiz one image to max
function imgmaxdimcenter( img, max )
{

	if( !isdefined( max ) ) return;
	if( !isdefined( img.tim ) ) img.tim = 0;
	if( img.tim < 10 && (img.width == 0 || img.clientWidth <= 0 ) )
	{
		img.tim++;
		setTimeout( function() { imgmaxdimcenter( img, max ); }, 100 );
		return;
	}
	imgmaxdim( img, max );
	img.style.position = 'relative';
	img.style.left = Math.floor( (max-img.clientWidth)/2 );
	img.style.top = Math.floor( (max-img.clientHeight)/2 );

}

var imgdebug = false;
// recise one image to max
function imgmaxdim(img, max)
{
	if( !isdefined( max ) ) return;
	if( !isdefined( img.tim ) ) img.tim = 0;
	if( img.tim < 10 && (img.width == 0 || img.clientWidth <= 0 ) )
	{
		img.tim++;
		setTimeout( function() { imgmaxdim( img, max ); }, img.tim * 20 + 1 );
		return;
	}
	var r = 1;
	if( !isdefined( img.nheight ) )
	{
		img.nheight = img.height;
		img.nwidth = img.width;
	}
	var w = img.nwidth;
	var h = img.nheight;
	if( w == -1 )
	{
		debug( 'reload', img.width );
		setTimeout( function() { imgmaxdim( img, max ) }, img.tim * 20 + 1 );
		return;
	}
	var w = img.nwidth;
	var h = img.nheight;
	var m = w > h ? w : h;
	if( m > max ) r = max/m;

	img.style.width = w = Math.floor( w*r );
	img.style.height = h = Math.floor( h*r );

	img.style.marginLeft = 0;
	img.style.marginTop = 0;
	var o = img.parentNode;
	if( typeof( o ) == 'Object' )
	{
		while( o != document.body && o.parentNode != null && o.onmouseover == null ) o = o.parentNode;
		if( isdefined( o.onmouseover ) ) o.title = img.title;
	}
	img.isloaded = true;
}

// make image fit in rectangle. If resized to better fit. 
function imgfit(img, maxw, maxh)
{
	if( !isdefined( maxw ) ) return;
	if( !isdefined( maxh ) ) return;
	if( !isdefined( img.tim ) ) img.tim = 0;
	if( img.tim < 10 && (img.width == 0 || img.clientWidth <= 0 ) )
	{
		img.tim++;
		setTimeout( function() { imgfit(img, maxw, maxh) }, img.tim * 20 + 1 );
		return;
	}
	var r = 1;
	if( !isdefined( img.nheight ) )
	{
		img.nheight = img.height;
		img.nwidth = img.width;
	}
	var w = img.nwidth;
	var h = img.nheight;
	if( w == -1 )
	{
		debug( 'reload', img.width );
		setTimeout( function() { imgfit(img, maxw, maxh) }, img.tim * 20 + 1 );
		return;
	}
	var w = img.nwidth;
	var h = img.nheight;
	var rw = maxw/w;
	var rh = maxh/h;
	var marw = 0;
	var marh = 0;
	if( rw < 0 || rh < 0 )
	{
		if( rw < rh )
		{
			r = rw;
			marh = Math.floor( (maxh-(h*r))/2 );
		}
		else
		{
			r = rh
			marw = Math.floor( (maxw-(w*r))/2 );
		}
	}
	else
		if( rw < rh )
		{
			r = rw;
			marh = Math.floor( (maxh-(h*r))/2 );
		}
		else
		{
			r = rh
			marw = Math.floor( (maxw-(w*r))/2 );
		}
	img.style.width = w = Math.floor( w*r );
	img.style.height = h = Math.floor( h*r );

	img.style.position = 'relative';
	img.style.left = marw;
	img.style.top = marh;
	img.style.marginLeft = 0;
	img.style.marginTop = 0;

//	img.style.marginLeft = marw;
//	img.style.marginTop = marh;
	var o = img.parentNode;
	if( typeof( o ) == 'Object' )
	{
		while( o != document.body && o.parentNode != null && o.onmouseover == null ) o = o.parentNode;
		if( isdefined( o.onmouseover ) ) o.title = img.title;
	}
	img.isloaded = true;
}



// frame a image to fit in a square with 'min' pixels
function imgsquare( img, min )
{
	if( !isdefined( min ) ) return;
	if( !isdefined( img.tim ) ) img.tim = 0;
	if( img.tim < 10 && (img.width == 0 || img.clientWidth <= 0 ) )
	{
		img.tim++;
		setTimeout( function() { imgsquare( img, min ); }, img.tim * 20 + 1 );
		return;
	}
	var r = 1;
	if( !isdefined( img.nheight ) )
	{
		img.nheight = img.height;
		img.nwidth = img.width;
	}
	var w = img.nwidth;
	var h = img.nheight;
	var m = w < h ? w : h;
	if( m > min ) r = min/m;

	img.style.width = w = Math.floor( w*r );
	img.style.height = h = Math.floor( h*r );


	var left;
	var top;
	if( w > min )
	{
		left = -Math.floor( (w - min)/2 );
		top = Math.floor( (min - h)/2 ); 
	}
	else if( h > min )
	{
		top = -Math.floor( (h - min)/2 );
		left = Math.floor( (min - w)/2 ); 
	}
	else
	{
		top = Math.floor( (min - h)/2 ); 
		left = Math.floor( (min - w)/2 ); 
	}
	img.style.position = 'relative';
	img.style.left = left;
	img.style.top = top;
	img.style.marginLeft = 0;
	img.style.marginTop = 0;
//	img.style.marginLeft = left;
//	img.style.marginTop = top;
//	debug( '<img style="border: 1px solid black" src="' + img.src + '">', img.clientWidth, img.clientHeight, img.style.left, img.style.top );
	var o = img.parentNode;

	if( typeof( o ) == 'Object' )
	{
		while( o != document.body && o.parentNode != null && o.onmouseover == null ) o = o.parentNode;
		if( isdefined( o.onmouseover ) ) o.title = img.title;
	}
	img.isloaded = true;
}




// adds a random parameter to a URL to avoid AJAX caching
function nocache( url )
{
	var ret;
	if( url.indexOf('?') > 0 )
		ret = url + '&rpar=' + Math.random();
	else
		ret = url + '?rpar=' + Math.random();
	return ret;
}

// get obj top position on document
function getTop(obj)
{
	var top = obj.offsetTop + obj.clientTop;
	while((obj = obj.offsetParent) != null && typeof( obj ) == 'object' && obj.tagName!='BODY')
	{
		top += obj.offsetTop - obj.scrollTop + obj.clientTop;
	}
	return top;
}


// get obj left position on document
function getLeft(obj)
{
	var left = obj.offsetLeft + obj.clientLeft;
	while((obj = obj.offsetParent) != null && typeof( obj ) == 'object' && obj.tagName!='BODY')
		left += obj.offsetLeft - obj.scrollLeft + obj.clientLeft;
	return left;
}

// make an AJAX request and cancel any other unfinished previous AJAX request
var uniqueajaxreq = -1;
function uniqueajax(url, callback_function, callback_param, return_xml )
{
	if( uniqueajaxreq >= 0 ) 
	{
		var uar = ajaxrequests[uniqueajaxreq];
		var ucancel = ajaxcancels[uniqueajaxreq];
		
		if( uar.readyState != 4 )
		{
			if( !ie ) uar.aborted = true;
			uar.abort();
			if( isdefined( ucancel ) ) ucancel();
			if( ckidle_timer ) clearTimeout( ckidle_timer );
//			debug( 'abort ajax', uniqueajaxreq.cancelfunc );
		}
	}
	uniqueajaxreq = ajaxrequest(url, callback_function, callback_param, return_xml );
	return uniqueajaxreq;
}

// set the 
function selectset( o, v )
{
	for( i = 0 ; i < o.options.length ; i++ )
	{
		if( o.options[i].text == v || o.options[i].value == v ) 
		{
			o.selectedIndex = i;
			return;
		}
	}
}



// bubble functions
var bubble_zidx = 1000;
var bubblecnt = 0;

function bubbleins( obj, ident )
{
	var dv = ce( 'DIV' );
	dv.className = ident;
	obj.appendChild( dv );
	return dv;
}

function bubblelize( obj, arrow, opacity )
{
	if( obj.done ) return;
	var width = obj.clientWidth;
	var height = obj.clientHeight;

	if( height < 30 ) obj.style.height = height = 30;
	var x = obj.left;
	var y = obj.top;
	var sx = x + '';
	var sy = y + '';
	if( sx.match( /%/ ) || sy.match( /%/ ) )
	{
		x = obj.offsetLeft;
		y = obj.offsetTop;
	}
	if( isdefined( obj.bubble ) && obj.bubble != null )
	{
		obj.bubble.parentNode.removeChild( obj.bubble );
		obj.bubble = null;
	}
	var bubble = ce( 'DIV' );
	bubble.className = 'bubble';
	bubble.style.top = -1000;
	bubble.style.left = -1000;
	obj.parentNode.appendChild( bubble );
	var ne = bubbleins( bubble, 'NE' );
	var nw = bubbleins( bubble, 'NW' );
	var se = bubbleins( bubble, 'SE' );
	var sw = bubbleins( bubble, 'SW' );
	var s = bubbleins( bubble, 'S' );
	var n = bubbleins( bubble, 'N' );
	var w = bubbleins( bubble, 'W' );
	var e = bubbleins( bubble, 'E' );
	var bg = bubbleins( bubble, 'bg' );
	var arr = bubbleins( bubble, 'pt' + arrow );
	if( isdefined( opacity ) )
	{
		var tmp = [ ne, nw, se, sw, s, n, w, e, bg, arr ];
		for( var i = 0 ; i < tmp.length ; i++ )
		{
			tmp[i].style.opacity=opacity;
			tmp[i].style.filter = 'alpha(opacity=' + opacity*100 + ')';
		}
	}

	var dw = e.clientWidth + w.clientWidth;
	var dh = n.clientHeight + s.clientHeight;

	bg.style.width = width;
	bg.style.height = height;
	bg.style.top = n.clientHeight;
	bg.style.left  = w.clientWidth;
	e.style.top = ne.clientHeight;

	var vh = height + dh - ne.clientHeight - se.clientHeight;
	if( vh <= 0 )
	{
		e.style.display = w.style.display = 'none';
	}
	e.style.height = vh;
	w.style.top = nw.clientHeight;
	w.style.height = vh;
	n.style.left = nw.clientWidth;
	n.style.width = width;
	s.style.left = sw.clientWidth;
	s.style.width = width;


	arrw = arrow.match( /W/ ) ? 8 : -8;
	var t, l;
	if( arrow == ''  )
	{
		arrw = 0;
		toleft = 0;
		tosouth = 0;
		t = bubble.style.top = y - n.clientHeight;
		l = bubble.style.left = x - w.clientWidth;
		bubble.style.width = width + dw;
		bubble.style.height = height + dh;
	}
	else
	{
		toleft = arrow.match( /E/ ) ? -(width + dw) : 0;
		tosouth = arrow.match( /S/ ) ? -(height + dh) : 0;
		obj.style.top = y + n.clientHeight + tosouth;
		obj.style.left = x + w.clientWidth + arrw + toleft;
		t = bubble.style.top = y - n.clientHeight + tosouth;
		l = bubble.style.left = x + arrw + toleft;
		bubble.style.width = width + dw;
		bubble.style.height = height + dh;
		var cornerdel = arrow.toLowerCase() + '.style.display=\'none\'';
		eval( cornerdel );
	}
	if( obj.bgdiv != null ) obj.bgdiv.style.zIndex = bubble_zidx++;
	bubble.style.zIndex = bubble_zidx++;

	if( isdefined( obj.shadow ) && obj.shadow != null )
	{
		obj.shadow.parentNode.removeChild( obj.shadow );
		obj.shadow = null;
	}
	var shadow = ce( 'DIV' );
	var w = bubble.clientWidth + 10;
	var h = bubble.clientHeight + 10;
	shadow.style.position = 'absolute';
	shadow.style.width = w;
	shadow.style.height = h;
	shadow.style.top = t-4;
	shadow.style.left = l-4;
	shadow.style.background = 'transparent';

	function sh_element( ident, top, left, width, height )
	{
		if( width <= 0 || height <= 0 ) return;
		var el = ce( 'DIV' );
		el.style.position = 'absolute';
		el.style.top = top;
		el.style.left = left;
		el.style.width = width;
		el.style.height = height;
		shadow.appendChild( el );
		if( ie )
		{
			el.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='./kintool/css/" + ident + ".png')";
		}
		else
		{
			el.style.background = 'transparent';
			el.style.backgroundImage = 'url( ./kintool/css/' + ident + '.png )';
		}
	}
	sh_element( 'sh_topleft', 0, 0, 26, 26 );
	sh_element( 'sh_topright', 0, w-26, 26, 26 );
	sh_element( 'sh_top', 0, 26, w-26*2, 26 );
	sh_element( 'sh_left', 26, 0, 26, h-26*2 );
	sh_element( 'sh_right', 26, w-26, 26, h-26*2 );
	sh_element( 'sh_botleft', h-26, 0, 26, 26 );
	sh_element( 'sh_botright', h-26, w-26, 26, 26 );
	sh_element( 'sh_bot', h-26, 26, w-26*2, 26 );

	bubble.style.zIndex = bubble_zidx++;
	obj.shadow = shadow;

	obj.parentNode.appendChild( shadow );


	obj.style.zIndex = bubble_zidx++;
	obj.bubble = bubble;
}

var bubblelist = [];
var errorlist=[];

function bubbleoutcheck( ev )
{
	if( ie ) ev = event;
	var target = ie ? ev.srcElement : ev.target;
	var inbubble = upDom( target, 'bubbleobj' ) != null;
	if( !inbubble )
	{
		nobubble();
		closeCalendar();
		document.body.onmousedown = null;
	}
	return true;
}

function sbubble( str, top, left, maxwidth, opacity, forcearr )
{
	var bcontent = ce('div');
	bcontent.className = 'bubblecontent';
	document.body.appendChild( bcontent );
	bcontent.maxwidth = maxwidth;
	bcontent.opacity = opacity;
	bcontent.forcearr = forcearr;
	bcontent.style.top = -1000;
	bcontent.style.left = -1000;
	bcontent.innerHTML = str;
	bcontent.top = top;
	bcontent.left = left;
	bcontent.bgdiv = null;
	var tmpwid = bcontent.clientWidth*1;
	if( tmpwid & 1 ) bcontent.style.width = tmpwid + 1;
	if( bcontent.clientWidth > maxwidth ) bcontent.style.width = maxwidth;
	if( ie )
	{
		var tmpheight = bcontent.clientHeight*1;
		if( tmpheight & 1 ) bcontent.style.height = tmpheight + 1;
	}
	var arr = top > bcontent.clientHeight + 20 ? 'S' : 'N';
	arr += left > 300 ? 'E' : 'W';
	if( isdefined( forcearr ) ) arr = forcearr;
	bubblelize( bcontent, arr, opacity );
	bcontent.id = 'bubble_' + bubblecnt;
	bcontent.bcount = bubblecnt++;
	bcontent.initop = top;
	bcontent.inileft = left;
	bubblelist.push( bcontent );
	bcontent.bubbleobj = bcontent;
	return bcontent;
}

function abubble( url, top, left, width, opacity, forcearr )
{
	nobubble();
	var bcontent = sbubble( '<div class="loading">&nbsp;&nbsp;Loading...</div>', top, left, width, opacity, forcearr );
	watch_animate( bcontent );
	bcontent.onchange = function() { bubbleresize( this ) };
	if( url != '' ) ajaxrequest( url, 'bubbleresult', bcontent, 0 );
	return bcontent;
}

function bubbleresize( obj )
{
	var maxwidth = obj.maxwidth;
	var opacity = obj.opacity;
	var forcearr = obj.forcearr;
	var top = obj.initop;
	var left = obj.inileft;
	var bcontent = obj;
	bcontent.style.height = '';
	bcontent.style.top = -1000;
	bcontent.style.left = -1000;
	if( bcontent.clientWidth > maxwidth ) bcontent.style.width = maxwidth;
	if( ie )
	{
		var tmpheight = bcontent.clientHeight*1;
		if( tmpheight & 1 ) bcontent.style.height = tmpheight + 1;
	}
	bcontent.style.top = top;
	bcontent.style.left = left;
	var arr = top > bcontent.clientHeight + 20 ? 'S' : 'N';
	arr += left > 300 ? 'E' : 'W';
	if( isdefined( forcearr ) ) arr = forcearr;
	bubblelize( obj, arr, opacity );
}

function bubbleresult( txt, obj )
{
	resultform( txt, obj );
	obj.style.width = 'auto';
	bubbleresize( obj );
}

function bubbleout( obj )
{
	if( !isdefined( obj ) ) return;
	if( isdefined( obj.gbdiv ) ) document.body.removeChild( obj.bgdiv );
	document.body.removeChild( obj.shadow );
	document.body.removeChild( obj.bubble );
	document.body.removeChild( obj );
	obj.done = true;
	for( var i = 0 ; i < bubblelist.length ; i++ )
		if( bubblelist[i] == obj )
			delete( bubblelist[i] );
}
function errorout( obj )
{
	if(!isdefined( obj )) return;
	var a=obj.parentNode;
	if( a != null)	a.removeChild( obj );

	for( var i = 0 ; i < errorlist.length ; i++ )
		if( errorlist[i] == obj )
			delete( errorlist[i] );

}
function noerror()
{
	var bub;
	while( isdefined( bub = errorlist.pop() ) )
		errorout( bub );
}

function nobubble()
{
	noerror();
	try
	{
		closeCalendar();
	}
	catch ( ev )
	{
	}
	var bub;
	while( isdefined( bub = bubblelist.pop() ) )
		bubbleout( bub );
}


function watch_animate( obj, num )
{
	if( obj == null || obj.parentNode == null || typeof( obj.offsetParent ) == 'unknown' || obj.offsetParent == null )
		return;
	if( !isdefined( num ) )
	{
		num = 0;
	}
	if( num > 6 ) num = 1;
	if( obj.className != 'loading' && obj.className != 'loading_button' )
	{
		var olist = obj.getElementsByTagName("DIV");
		var i;
		for( i = 0 ; i < olist.length ; i++ )
		{
			if( olist[i].className == 'loading' )
			{
				obj = olist[i];
				break;
			}
		}
	}
	if( num > 0 )
	{
		obj.style.display = 'block';
		if( ie )
		{
			if( !isdefined( obj.iebg ) )
			{
				var top = parseInt(obj.currentStyle.backgroundPositionY);
				var left = parseInt(obj.currentStyle.backgroundPositionX);
				obj.style.backgroundImage = 'none';
				obj.style.background = 'transparent';
				var loaddiv = ce( 'DIV' );
				loaddiv.iebg = true;
				loaddiv.style.position = 'absolute';
				loaddiv.style.top = top;
				loaddiv.style.left = left;
				loaddiv.style.width = 20;
				loaddiv.style.height = 20;
				obj.appendChild( loaddiv );
				if( obj.currentStyle.position == 'static') obj.style.position = 'relative';
				obj = loaddiv;
			}
			obj.style.filter = 	"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='crop', src='./kintool/css/watch000" + num + ".png')";
		}
		else
		{
			obj.style.backgroundImage = 'url( ./kintool/css/watch000' + num + '.png )';
		}
//		setTimeout( function() { watch_animate( obj, num+1 ) }, 100 );
	}
	else
	{
//		setTimeout( function() { watch_animate( obj, num+1 ) }, 300 );
	}
	setTimeout( function() { watch_animate( obj, num+1 ) }, 100 );
}


function plural( v, sing, plr )
{
	if( isdefined( sing ) )
		return v == 1 ? sing : plr;
	else
		return v == 1 ? '' : 's';
}

function bodycenter( val )
{
	if(!isdefined(val))
		val=1024;

	var cw = document.body.clientWidth;
	var mrg = Math.floor((cw - val)/2);
	if( mrg < 0 ) mrg = 0;
	document.body.style.marginLeft = mrg;
	document.body.mrg = mrg;
	//document.body.style.paddingBottom = 80;
//	if( ie )
//		document.body.style.height = document.body.clientHeight;
//	else
//		document.body.style.minHeight = document.body.clientHeight;
//		document.body.style.height = document.body.clientHeight;
	if( !isdefined( window.onresize ) || window.onresize == null ) window.onresize = function() { bodycenter() };
}


function execcommand( url )
{
	ajaxrequest( url, formresult, $('command'), 1, 'POST', '' );
}

function logout()
{
	execcommand( 'services/Account/logout' );
}

function corporate_logout()
{
	execcommand( 'services/Account/clogout' );
}
// returns a file link from the file array returned by service
// if empty or not found, return the noimage.gif
function getfilepath( arr, ident, thumb )
{
	var suffix = '';
	if( thumb ) suffix = 'th';
	for( var i = 0 ; i < arr.length ; i++ )
	{
		if( arr[i][1] == ident )
			return 'services/service.php?$serviceName=Items&$operation=file&id=' + arr[i][0] + '&suffix=' + suffix;
	}
	return 'kintool/' + csspath + '/noimage.gif';
}

function addclass( o, cls )
{
	var cn = o.className + ' ';
	cn += cls;
	o.className = cn;	
}


function removeclass( o, cls )
{
	var cn = o.className + '';
	cn = eval( 'cn.replace( / ' + cls + '/g, \'\' )' );
	o.className = cn;
}

// image preload functions
// add images to a preload queue. This will preload gradualy the new images

var preloadimg_queue = [];
var preloadimg_queued = [];
var preloadimgs = [];

function preloadimg( url )
{
	var first = preloadimg_queue.length == 0;
	if( !preloadimg_queued[url] )
	{
		preloadimg_queued[url] = true;
		preloadimg_queue.push( url );
	}
	if( first )	setTimeout( preloadimg_next, 1 );
}

function preloadimg_next()
{
	if( preloadimg_queue.length == 0 ) return;
//	debug( 'pnext', preloadimg_queue.length );
	var url = preloadimg_queue.shift();
	var img = new Image;
	preloadimgs.push( img );
	img.onload = function() { setTimeout( preloadimg_next, 1 ); };
	img.src = url;
}

function modal( onoff, func, param )
{
	if( onoff )
	{
		var div = ce( 'DIV' );
		div.className = 'modal';
		div.id = 'modaldiv';
		document.body.appendChild( div );
		var cw = document.body.clientWidth;
		var ch = document.body.scrollHeight;
		div.style.width = cw;
		div.style.height = ch;
		if( !ie ) div.style.left = -document.body.mrg;
		if( isdefined( func ) )
		{
			div.onclick = function() { func( param ) };
		}
	}
	else
	{
		var div = $('modaldiv');
		if( div != null )
			document.body.removeChild( div );
	}
}


function logoclick( ev )
{
	if( ie ) ev = event;

	if( ev.ctrlKey && ev.shiftKey )
	{
		ajaxdebug = !ajaxdebug;
		debug( 'Ajaxdebug', ajaxdebug );
		savevar( 'ajaxdebug', ajaxdebug );
	}
	else
		document.location = 'index.php';
}


var lastSavedName, lastSavedVal;
function savevar( name, val, permanent )
{
	if( name == lastSavedName && val == lastSavedVal ) return;

	lastSavedName = name;
	lastSavedVal = val;

	if( !isdefined( permanent ) ) permanent = '';
	ajaxrequest('savevar.php?name=' + name + '&val=' + val + '&permanent=' + permanent, null, null, 0 );
	var ev = '';
	if( typeof( val ) == 'number' || typeof( val ) == 'boolean' )
		ev = name + '= ' + val + ';';
	else
	{
		val = val.replace( /"/g, '\\"' );
		ev = name + ' = "' + val + '";';
	}
	eval( ev );
}

function getGMT()
{
	data = new Date();

	var minutes = data.getTimezoneOffset();

	if(minutes<0) minutes=-minutes;

	data.setHours(0);
	data.setMinutes(minutes);

	var hours="";
	var minutes="";

	if(data.getHours()<10)
		hours="0"+data.getHours();
	else
		hours=data.getHours();

	if(data.getMinutes()<10)
		minutes="0"+data.getMinutes();
	else
		minutes=data.getMinutes();

	var result=data.toGMTString();
	result=result.substring(17,19);
	result=parseInt(data.getHours())-parseInt(result);

	var op="+";
	if(result<0)
		op="-";

	result = op+hours+":"+minutes;

	return result;
}
var browsername=null;
function browserCSS()
{
	var nav = navigator.userAgent.toLowerCase();
	var browsertype = [ 'chrome', 'firefox', 'msie', 'safari' ];
	var browser = [];
	for( var i = 0 ; i < browsertype.length ; i++ )
		if( nav.indexOf( browsertype[i] ) >= 0 ) browser.push( browsertype[i] );

	html = document.getElementsByTagName('html')[0];
	var bclass = browser.join( ' ' );
	if( !ie && bclass.indexOf( 'chrome' ) >= 0 )
	{
		bclass = bclass.replace( /safari/, '' );
		chrome = true;
	}
	if( !ie && bclass.indexOf( 'safari' ) >= 0 )
		safari = true;
	if( !ie && bclass.indexOf( 'firefox' ) >= 0 )
		firefox = true;
	browsername = bclass;
	if( bclass.indexOf( 'msie' ) >= 0 ) 
		browsername = bclass = bclass.replace( /msie/, 'ie' );
	else
		bclass += ' not_ie';

	soclass= ' win ';
	if( navigator.appVersion.lastIndexOf( 'Mac' ) != -1 )
		soclass= ' mac';
	if( navigator.appVersion.lastIndexOf( 'Linux' ) != -1 )
		soclass= ' linux';

	html.className = soclass+bclass;
}

function goTop()
{
	if($('topme')!=null)
		$('topme').innerHTML="<input type='text' id='inpt_topme' name='inpt_topme' style='width:1px; height:1px; border:0px; margin:0px; padding:0px;'/>";
	if($('inpt_topme')!=null)
		$('inpt_topme').focus();
	if($('topme')!=null)
		$('topme').innerHTML="";
}
function is_numeric(input){
	/*
	if((typeof(input)=='number') || (typeof(input)=='string' && input.match(/[^0-9]/)==null))
		return 1;
	return 0;
	*/
	 if (input === '') 
        return false; 

    return !isNaN(input * 1);
  }
 

function html_entity_decode( string, quote_style ) {
    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 get_html_translation_table(table, quote_style) {

    var entities = {}, histogram = {}, 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 Error("Table: "+useTable+' not supported');
        // return false;
    }
 
    // ascii decimals for better compatibility
    entities['38'] = '&amp;';
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
 
    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;';
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

function shrinktext( classname, maxheight, stext, maximizescript, moreflag, width )
{
//    return stext;
   var tmp = ce( 'div' );
   var more = moreflag ? ' ... <a href="javascript:'+ maximizescript + '">(more)</a>' : '...';
   tmp.className = classname;
   tmp.style.position = 'absolute';
   tmp.style.left = -10000;

   if( isdefined( width ) ) tmp.style.width = width;
      document.body.appendChild( tmp );
   tmp.innerHTML = stext;
   dim = 5;
   while( 1 && tmp.clientHeight > maxheight )
   {
       stext = stext.substring( 0, stext.length - dim );
       while( stext.charAt(stext.length-1).match( /[a-zA-Z<]/ ) )
           stext = stext.substring( 0, stext.length - 1 );
       stext += more;
       if( dim < more.length ) dim += more.length;
       tmp.innerHTML = stext;
   }
   document.body.removeChild( tmp );
   return stext;
} 
function random(inferior,superior){ 
   	numPossibilidades = superior - inferior 
   	aleat = Math.random() * numPossibilidades 
   	aleat = Math.round(aleat) 
   	return parseInt(inferior) + aleat 
} 
function convertDateFromMysql( date )
{
	return date.substr(5,2)+'/'+date.substr(8,2)+'/'+date.substr(0,4);
}

var ajaxhistoryold = new function()
{
	this.history_stack = []
	this.history_num = 0;
	this.tid = null;

	var dom_events =
	['onblur', 'onfocus', 'oncontextmenu', 'onload',
	'onresize', 'onscroll', 'onunload', 'onclick',
	'ondblclick', 'onmousedown', 'onmouseup', 'onmouseenter',
	'onmouseleave', 'onmousemove', 'onmouseover',
	'onmouseout', 'onchange', 'onreset', 'onselect',
	'onsubmit', 'onkeydown', 'onkeyup', 'onkeypress',
	'onabort', 'onerror'];

	function dom_obj(o) { return o != null & typeof( o.tagName ) != 'undefined' };

	function cloneFix(o, copy) 
	{
		if (!(dom_obj(o) && dom_obj(copy))) { return; }
	   
		for (var i = 0;i < dom_events.length;i++)
		{
			var event = dom_events[i];
			if (event in o) { copy[event] = o[event]; }
		}
		if ('value' in o) { copy.value = o.value; }
	   
		var o_kids = o.childNodes;
		var c_kids = copy.childNodes;
		for (i = 0;i < o_kids.length;i++)
			cloneFix(o_kids[i], c_kids[i]);
	}

	function mark( objs, func )
	{
		var num = new Date().getTime();
		if( !isdefined( func ) ) func = null;

		var a = ce( 'DIV' );
		a.style.position = 'absolute';
		a.style.left = 0;
		a.style.width = 10;
		a.style.overflow = 'hidden';
		a.style.top = document.body.scrollTop;
		a.innerHTML = '<a name="MB_' + num + '">&nbsp;</a>';

		if( !isdefined(objs.length) ) // if is not an array
			objs = [ objs ];

		var urls = [];
		for( var i = 0 ; i < objs.length ; i++ )
			urls[i]  = objs[i].url;

		document.body.appendChild( a );

		ajaxhistory.history_stack.push( {'objs':objs,'urls':urls,'num':ajaxhistory.history_num,'func':func} );
		ajaxhistory.history_num = num;

		document.location = '#MB_' + num;

		function removeA() { document.body.removeChild( a ); }
		setTimeout( removeA, 30 );

//		if( ie ) inspect( document );
		if( ajaxhistory.tid == null ) ajaxhistory.back_ck( this );
	};

	function back_ck( obj )
	{
		var loc = document.location + '';
		var lnum = loc.match( /#MB_(\d*)/ );
		if( lnum != null ) lnum = lnum[1];
		else lnum = 0;

		var backbutton = false;
		if( ie )
		{
			var url = document.URLUnencoded + '';
//			debug( 'url', url );
			if( !url.match( /#/ ) )
				backbutton = true;
		}
		else if( lnum < ajaxhistory.history_num )
			backbutton = true;

		if( backbutton )
			ajaxhistory.back();
		ajaxhistory.tid = setTimeout( ajaxhistory.back_ck, 100 );
	};

	function back()
	{
		if( ie ) document.URL += '#';
		var bck = ajaxhistory.history_stack.pop();
		ajaxhistory.history_num = bck.num;
		for( var i = 0 ; i < bck.objs.length ; i++ )
		{
			if( isdefined( bck.urls[i] ) && bck.urls[i] > '' )
				loadurl( bck.urls[i], bck.objs[i] );
		}
		if( bck.func != null ) bck.func();
	}
	this.back = back;
	this.mark = mark;
	this.back_ck = back_ck;
	return this;
}


var ajaxhistory = new function()
{
	this.history_stack = []
	this.history_num = 0;
	this.tid = null;
	this.count = 0;
	this.iframe = null;
	this.hash = {};
	this.ckcount = 0;

	function init()
	{
		if( this.iframe == null )
		{
			this.iframe = ce( 'IFRAME' );
			this.iframe.style.display = 'none'
			this.iframe.id = 'historyiframe';
			document.body.appendChild( this.iframe );
			this.iframe.contentWindow.document.location = 'kintool/blank.html?0#start';
		}
	}

	function mark( objs, func )
	{
		var num = new Date().getTime();
		if( !isdefined( func ) ) func = null;
		if( this.iframe == null ) this.init();

		if( !isdefined(objs.length) ) // if is not an array
			objs = [ objs ];

		var urls = [];
		for( var i = 0 ; i < objs.length ; i++ )
			urls[i]  = objs[i].url;

		ajaxhistory.history_stack.push( {'objs':objs,'urls':urls,'num':ajaxhistory.history_num,'func':func} );
		ajaxhistory.history_num = num;

		this.count++;
		this.newloc = 'kintool/blank.html?' + (this.count%2) + '#MB_' + num;
		this.iframe.contentWindow.document.location = this.newloc;
	};

	function back()
	{
		this.count--;
		var bck = ajaxhistory.history_stack.pop();
		ajaxhistory.history_num = bck.num;
		for( var i = 0 ; i < bck.objs.length ; i++ )
		{
			if( isdefined( bck.urls[i] ) && bck.urls[i] > '' )
				loadurl( bck.urls[i], bck.objs[i] );
		}
		if( bck.func != null ) bck.func();
	}

	function ck( hash )
	{
		var ok = this.hash[hash] == 1;
//		debug( 'ck', hash, hash.length, ok );
		this.hash[hash] = 1;
		if( ok ) this.back();
	}
	this.back = back;
	this.mark = mark;
	this.ck = ck;
	this.init = init;
	return this;
}


function getPageSize()
{
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
    
	arrayPageSize = [w,h];
    return arrayPageSize;
} 
function infobubble(str, maxwidth )
{
	maxwidth = 300;
	arr = getPageSize();

	t = arr[1]/2 - 40;
	l = arr[0]/2 - 300;
	
	if(ie)
	{
		var aux = document.body.style.marginLeft;
		l += aux.substring(0,aux.length-2)*1;
	}

	str = '<div style="width:'+maxwidth+'px; margin: 20px 10px 20px 10px; text-align: center;">'+str+'</div>';
	bub = sbubble( str, t, l, maxwidth, 100, 'S' );

	setTimeout(function(){getBubble(bub);}, 1300);
}
function getBubble(bub)
{
	fadeoutaux( bub , 10 );
	if( isdefined( bub.gbdiv ) ) document.body.removeChild( bub.bgdiv );
	if( isdefined( bub.shadow ) ) document.body.removeChild( bub.shadow );
}
function fadeoutaux( obj , num)
{
	if( !isdefined( obj ) ) return;
	if(num>1)
	{
		setOpacity(obj.bubble, num);
		setOpacity(obj, num);

		setTimeout(function(){ fadeoutaux(obj, --num); }, 60);
	}
	else if(num==1 || num==0)
	{	
		if( isdefined( obj.bubble ) ) document.body.removeChild( obj.bubble );
		document.body.removeChild( obj );
		
		for( var i = 0 ; i < bubblelist.length ; i++ )
			if( bubblelist[i] == obj )
				delete( bubblelist[i] );
	}
	obj.done = true;
}

function setOpacity(obj, value) {
	if(obj==null) return;
	obj.style.opacity = value/10;
	obj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

browserCSS();



